package com.xbongbong.saas.service.impl;

import com.alibaba.dingtalk.openapi.message.OAMessage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.message.domain.entity.PushEntity;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.HomePageCustomTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.UnitEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.manager.feign.ChartCategoryFeignClient;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.KeyValuePojo;
import com.xbongbong.paas.pojo.StageFindPojo;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.service.CompanyService;
import com.xbongbong.paas.service.HomePageManageService;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.service.UserConfigService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.app.pojo.AppMenuFormIdPojo;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.PackageConstant;
import com.xbongbong.pro.constant.RaidersConstant;
import com.xbongbong.pro.constant.SymbolConstant;
import com.xbongbong.pro.domain.entity.ActivityEntity;
import com.xbongbong.pro.domain.entity.ChartCategoryEntity;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.domain.entity.HomePageManageEntity;
import com.xbongbong.pro.domain.entity.IndexFilterEntity;
import com.xbongbong.pro.domain.entity.IndexSetEntity;
import com.xbongbong.pro.enums.ActivityTypeEnum;
import com.xbongbong.pro.enums.BoardTypeEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.TimeTypeEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.StatisticsServicesErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.homePageManage.pojo.dto.HomePageManageSaveDTO;
import com.xbongbong.pro.index.pojo.IndexBoardChartPojo;
import com.xbongbong.pro.index.pojo.IndexBoardChartSavePojo;
import com.xbongbong.pro.index.pojo.IndexBoardGetConfigAppPojo;
import com.xbongbong.pro.index.pojo.IndexBoardSaveItemPojo;
import com.xbongbong.pro.index.pojo.IndexFilterDataPojo;
import com.xbongbong.pro.index.pojo.IndexInitPojo;
import com.xbongbong.pro.index.pojo.IndexSetDataPojo;
import com.xbongbong.pro.index.pojo.dto.IndexBoardChartGetConfigDTO;
import com.xbongbong.pro.index.pojo.dto.IndexBoardChartSaveConfigDTO;
import com.xbongbong.pro.index.pojo.dto.IndexBoardGetConfigDTO;
import com.xbongbong.pro.index.pojo.dto.IndexBoardHideDTO;
import com.xbongbong.pro.index.pojo.dto.IndexBoardInitDTO;
import com.xbongbong.pro.index.pojo.dto.IndexBoardSaveConfigAppDTO;
import com.xbongbong.pro.index.pojo.dto.IndexBoardSaveConfigDTO;
import com.xbongbong.pro.index.pojo.dto.IndexBoardSaveConfigWebDTO;
import com.xbongbong.pro.index.pojo.dto.IndexBoardSaveSingleConfigAppDTO;
import com.xbongbong.pro.index.pojo.dto.IndexSaveFilterDTO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardChartGetConfigVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardChartSaveConfigVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardGetConfigAppVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardGetConfigVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardGetConfigWebVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardHideVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardInitAppVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardInitVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardInitWebVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardSaveConfigVO;
import com.xbongbong.pro.index.pojo.vo.IndexBoardSaveSingleConfigVO;
import com.xbongbong.pro.index.pojo.vo.IndexSaveFilterVO;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.service.MessageListService;
import com.xbongbong.pro.service.stage.StageFindStrategy;
import com.xbongbong.pro.service.stage.factory.StageFindFactory;
import com.xbongbong.pro.service.toolbox.statistic.help.ChartPermissionHelp;
import com.xbongbong.pro.service.toolbox.statistic.help.ChartPkRuleHelp;
import com.xbongbong.pro.service.toolbox.statistic.help.FiscalYearHelp;
import com.xbongbong.pro.service.toolbox.statistic.help.PkRuleHelp;
import com.xbongbong.pro.service.toolbox.statistic.help.SystemChartHelp;
import com.xbongbong.pro.service.toolbox.statistic.util.ChartResultUtil;
import com.xbongbong.pro.statistic.constant.ChartConstant;
import com.xbongbong.pro.statistic.enums.ChartCategoryAliasEnum;
import com.xbongbong.pro.statistic.enums.ChartCategoryTypeEnum;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.enums.NumFormatEnum;
import com.xbongbong.pro.statistic.enums.StatisticsTypeEnum;
import com.xbongbong.pro.statistic.enums.SystemCodeEnum;
import com.xbongbong.pro.statistic.model.ChartCategoryModel;
import com.xbongbong.pro.statistic.model.ChartCustomModel;
import com.xbongbong.pro.statistic.model.ChartModel;
import com.xbongbong.pro.statistic.pojo.FiscalYearTimePojo;
import com.xbongbong.pro.statistic.pojo.dto.ChartCategoryInitDTO;
import com.xbongbong.pro.statistic.pojo.vo.ChartCategoryInitVO;
import com.xbongbong.pro.statistic.result.pojo.ChartIdPojo;
import com.xbongbong.pro.statistic.result.pojo.PkInfoPojo;
import com.xbongbong.pro.statistic.result.pojo.PkPerforInfoPojo;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultDetailVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultPkDetailVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartResultValueDetailVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultChartVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultDataChartVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultDataSeriesChartVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultDataTableVO;
import com.xbongbong.pro.statistic.result.pojo.vo.ResultTableVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.help.IndexHelp;
import com.xbongbong.saas.help.MarketManagementBusinessHelp;
import com.xbongbong.saas.model.CustomerStageModel;
import com.xbongbong.saas.model.HomePageManageModel;
import com.xbongbong.saas.model.IndexFilterModel;
import com.xbongbong.saas.model.IndexSetModel;
import com.xbongbong.saas.model.SaleStageModel;
import com.xbongbong.saas.service.ActivityService;
import com.xbongbong.saas.service.IndexService;
import com.xbongbong.saas.service.toolbox.help.UpdatePackageRedisService;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.CompanyStructTypeEnum;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.impl.UserModelImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @description: 首页看板
 * @Author: hongxiao
 * @date: 2019-02-27 10:31
 * @since v1.0
 */
@Service("indexService")
public class IndexServiceImpl implements IndexService {
    private static final Logger LOG = LoggerFactory.getLogger(IndexServiceImpl.class);
    /**
     * 指标最大数量
     */
    private static final int CHART_MAX_COUNT = 12;
    /**
     * web端左侧看板数量
     */
    private static final int WEB_LEFT_BOARD_COUNT = 25;
    /**
     * app端看板数量
     */
    private static final int DINGTALK_BOARD_COUNT = 40;

    private List<String> dateTitleList;

    @Resource
    private IndexSetModel indexSetModel;
    @Resource
    private IndexFilterModel indexFilterModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private ChartModel chartModel;
    @Resource
    private ChartCustomModel chartCustomModel;
    @Resource
    private ChartCategoryModel chartCategoryModel;
    @Resource
    private ChartCategoryFeignClient chartCategoryFeignClient;
    @Resource
    private SaleStageModel saleStageModel;
    @Resource
    private ActivityService activityService;
    @Resource
    private MessageListService messageListService;
    @Resource
    private IndexHelp indexHelp;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private ChartPermissionHelp chartPermissionHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private SystemChartHelp systemChartHelp;
    @Resource
    private CustomerStageModel customerStageModel;
    @Resource
    private UserModelImpl userModel;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private ChartPkRuleHelp chartPkRuleHelp;
    @Resource
    private CompanyService companyService;
    @Resource
    private MarketManagementBusinessHelp marketManagementBusinessHelp;
    @Resource
    private PkRuleHelp pkRuleHelp;
    @Resource
    private UpdatePackageRedisService updatePackageRedisService;
    @Resource
    private HomePageManageModel homePageManageModel;
    @Resource
    private HomePageManageService homePageManageService;
    @Resource
    private UserConfigService userConfigService;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PaasAppModel paasAppModel;

    public void filter(ChartCategoryInitVO companyData,ChartCategoryInitVO dingTalkCompanyData,ChartCategoryInitVO focusDingTalkCompanyData,String corpid,UserVO loginUser,
                       List<IndexSetDataPojo> leftSetDataList,List<IndexSetDataPojo> rightSetDataList,List<IndexSetDataPojo> dingTalkSetDataList,List<IndexSetDataPojo> focusDingTalkCategorySetDataList,
                       List<IndexSetDataPojo> focusDingTalkWorkSetDataList) throws XbbException {
        // 套餐过滤
        boolean standardWithFeeType = marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(corpid);
        Integer feeType = packageHelp.getFeeType(corpid);

        List<ChartCategoryEntity> categoryList = null != companyData ? companyData.getCategoryList() : null;
        List<ChartCategoryEntity> dingTalkCategoryList = null != dingTalkCompanyData ? dingTalkCompanyData.getCategoryList() : null ;
        List<ChartCategoryEntity> focusDingTalkCategoryList = null != focusDingTalkCompanyData ? focusDingTalkCompanyData.getCategoryList() : null;

        if (!Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())){
            // 防止降套餐，降到低级版套餐还有数据预警
            if (CollectionUtils.isNotEmpty(categoryList)){
                Iterator<ChartCategoryEntity> iterator = categoryList.iterator();
                while (iterator.hasNext()){
                    String alias = iterator.next().getAlias();
                    if (standardWithFeeType && Objects.equals(alias, "saleClue")) {
                        continue;
                    }
                    if (Objects.equals(alias, ChartCategoryAliasEnum.DATA_WARNING.getAlias())) {
                        iterator.remove();
                        break;
                    }
                }
            }

            // 防止降套餐，降到低级版套餐还有数据预警
            if (CollectionUtils.isNotEmpty(dingTalkCategoryList)){
                Iterator<ChartCategoryEntity> dingTalkIterator = dingTalkCategoryList.iterator();
                while (dingTalkIterator.hasNext()){
                    String alias = dingTalkIterator.next().getAlias();
                    if (Objects.equals(alias, ChartCategoryAliasEnum.DATA_WARNING.getAlias())) {
                        dingTalkIterator.remove();
                        break;
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(focusDingTalkCategoryList)){
                Iterator<ChartCategoryEntity> focusDingTalkIterator = focusDingTalkCategoryList.iterator();
                while (focusDingTalkIterator.hasNext()){
                    String alias = focusDingTalkIterator.next().getAlias();
                    if (Objects.equals(alias, ChartCategoryAliasEnum.DATA_WARNING.getAlias())) {
                        focusDingTalkIterator.remove();
                        break;
                    }
                }
            }
        }


        // TODO 过滤权限相关
        Set<Long> depIdIn = chartPermissionHelp.getAllDeptIds(loginUser);

        if (null != companyData){
            //把最新的分类list置入
            companyData.setCategoryList(categoryList);
            //把获取到的分类、图表封装塞入 companyData 内的对应map
            formatCompanyData(loginUser, companyData);
            checkPermission(loginUser, depIdIn, leftSetDataList, rightSetDataList, companyData);
            // 过虑超出的数量
            if (leftSetDataList.size() > WEB_LEFT_BOARD_COUNT) {
                leftSetDataList = leftSetDataList.subList(0, WEB_LEFT_BOARD_COUNT);
            }
        }
        if (null != focusDingTalkCompanyData){
            focusDingTalkCompanyData.setCategoryList(focusDingTalkCategoryList);
            formatCompanyData(loginUser, focusDingTalkCompanyData);
            checkPermission(loginUser, depIdIn, focusDingTalkCategorySetDataList, focusDingTalkWorkSetDataList, focusDingTalkCompanyData);
        }
        if (null != dingTalkCompanyData){
            dingTalkCompanyData.setCategoryList(dingTalkCategoryList);
            formatCompanyData(loginUser, dingTalkCompanyData);
            checkPermission(loginUser, depIdIn, dingTalkSetDataList, null, dingTalkCompanyData);
        }
    }

    private void setDateRelated(UserVO userVO,String corpid,String userId,IndexBoardInitVO boardInitVO){
        // 当前权限
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, true);
        // 筛选项数据
        IndexFilterDataPojo filterDataPojo = getFilterData(corpid, userId, userVO.getName(), dataPermission);
        int startMonth = companyConfigModel.getFiscalStartMonth(corpid);

        // x轴坐标数据（图表用）
        dateTitleList = getDateTitleLis(filterDataPojo, filterDataPojo.getTimeType(), startMonth);

        // 相关权限(财年，老板，销售）
        boolean isFiscalYear = startMonth != BasicConstant.MIN_MONTH;
        boolean isBoss = DataPermissionEnum.ALL.getCode().equals(dataPermission);
        boolean isSales = DataPermissionEnum.SELF.getCode().equals(dataPermission);

        boardInitVO.setFilterContent(filterDataPojo);
        boardInitVO.setIsFiscalYear(isFiscalYear);
        boardInitVO.setIsBoss(isBoss);
        boardInitVO.setIsSales(isSales);

    }

    private void setDateRelated(UserVO userVO,String corpid,String userId,IndexBoardGetConfigWebVO getConfigWebVO){
        // 当前权限
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, true);
        // 筛选项数据
        IndexFilterDataPojo filterDataPojo = getFilterData(corpid, userId, userVO.getName(), dataPermission);
        int startMonth = companyConfigModel.getFiscalStartMonth(corpid);

        // x轴坐标数据（图表用）
        dateTitleList = getDateTitleLis(filterDataPojo, filterDataPojo.getTimeType(), startMonth);

        // 相关权限
        boolean isBoss = DataPermissionEnum.ALL.getCode().equals(dataPermission);

        getConfigWebVO.setIsBoss(isBoss);
        getConfigWebVO.setUserName(filterDataPojo.getUserName());
        getConfigWebVO.setTimeName(filterDataPojo.getTimeName());

    }
    @Override
    public IndexBoardInitVO boardInitWeb(IndexBoardInitDTO boardInitDTO) throws XbbException {

        IndexBoardInitWebVO boardInitWebVO = new IndexBoardInitWebVO();

        String corpid = boardInitDTO.getCorpid();
        String userId = boardInitDTO.getUserId();
        String platform = boardInitDTO.getPlatform();
        UserVO userVO = boardInitDTO.getLoginUser();
        Long homePageId = boardInitDTO.getHomePageId();

        // 获取个人配置
        List<IndexSetDataPojo> leftDBList;
        List<IndexSetDataPojo> rightDBList;
        if (null != homePageId){
            leftDBList = systemChartHelp.getCustomConfig(corpid, homePageId, BoardTypeEnum.WEB_LEFT.getAlias());
            rightDBList = systemChartHelp.getCustomConfig(corpid, homePageId, BoardTypeEnum.WEB_RIGHT.getAlias());
        }else {
            leftDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.WEB_LEFT.getCode());
            rightDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.WEB_RIGHT.getCode());
        }

        // 是否是初始化公司
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("userId", "0");
        param.put("del", DelEnum.NORMAL.getDel());
        Integer count = indexSetModel.getEntitysCount(param);
        Boolean isCustom = false;
        if (null != homePageId){
            // 自定义首页不要走初始化公司逻辑
            count = 1;
            isCustom = true;
        }

        // 获取公司配置
        List<IndexSetDataPojo> leftCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.WEB_LEFT.getCode());
        List<IndexSetDataPojo> rightCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.WEB_RIGHT.getCode());
        // 过虑配置
        List<IndexSetDataPojo> leftSetDataList = checkConfig4Show(leftCompanyList, leftDBList,corpid,BasicConstant.ZERO,isCustom);
        List<IndexSetDataPojo> rightSetDataList = checkConfig4Show(rightCompanyList, rightDBList,corpid,BasicConstant.ONE,isCustom);


        // 获取当前数据
        ChartCategoryInitVO companyData = getCompanyData(corpid, userId, platform, leftSetDataList, rightSetDataList);

        // 权限等过滤
        filter(companyData,null,null,corpid,boardInitDTO.getLoginUser(),leftSetDataList,rightSetDataList,null,null,null);

        // 日期相关设置
        setDateRelated(userVO,corpid,userId, boardInitWebVO);

        List<IndexInitPojo> leftList = formatInitWeb(boardInitDTO.getLoginUser(), leftSetDataList, companyData, count, BasicConstant.ZERO,isCustom);
        List<IndexInitPojo> rightList = formatInitWeb(boardInitDTO.getLoginUser(), rightSetDataList, companyData, count, BasicConstant.ONE,isCustom);

        addFlag4WorkOrderV2(corpid, leftList);
        //判断新工单是否开启应用过滤右侧看板
        checkWorkOrderV2IsUse(corpid,rightList);
        // 公告处理
//        checkAnnouncementPojo(rightList, corpid);

        // 访客计划权限处理
        setCommunicatePlanPermission(rightList,boardInitWebVO);

        // 销售简报处理
        JSONObject salesReport = getSalesReport(corpid, userId, rightList);

        boardInitWebVO.setLeftList(leftList);
        boardInitWebVO.setRightList(rightList);
        if (salesReport != null) {
            boardInitWebVO.setSalesReport(salesReport);
        }
        // 是否有页面定制
        boolean hasCustomPage = boardInitDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.CUSTOM_PAGE.getAlias());
        boardInitWebVO.setHasCustomPage(hasCustomPage);
        return boardInitWebVO;
    }

    private void checkWorkOrderV2IsUse(String corpid, List<IndexInitPojo> rightList) throws XbbException{
        Boolean isUse = paasAppModel.validateAppEnable(null, XbbRefTypeEnum.WORK_ORDER_V2_CENTER.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
        if (!isUse){
            if (CollectionUtils.isNotEmpty(rightList)){
                Iterator<IndexInitPojo> rightIterator = rightList.iterator();
                while (rightIterator.hasNext()){
                    String alias = rightIterator.next().getAlias();
                    if (Objects.equals(alias, ChartCategoryAliasEnum.PENDING_WORK_ORDER_V2.getAlias())) {
                        rightIterator.remove();
                        break;
                    }
                }
            }
        }
    }

    /**
     * 为新工单添加标识（给前端跳转新工单接口用）
     * @param corpid
     * @param leftList
     */
    private void addFlag4WorkOrderV2(String corpid, List<IndexInitPojo> leftList) {
        if (leftList.isEmpty()) {
            return;
        }
        ChartEntity systemChartByCode = chartModel.getSystemChartByCode(corpid, SystemCodeEnum.WORK_ORDER_V2_COMPLETION_NUM);
        if (Objects.isNull(systemChartByCode)) {
            return;
        }
        for (IndexInitPojo leftPojo : leftList) {
            if (!Objects.equals("pk", leftPojo.getAlias())) {
                continue;
            }
            List<ChartResultPkDetailVO> chartResultPkDetailVOS = JSONArray.parseArray(JSON.toJSONString(leftPojo.getChildList()), ChartResultPkDetailVO.class);
            boolean updateFlag = false;
            for (ChartResultPkDetailVO chartResultPkDetailVO : chartResultPkDetailVOS) {
                if (Objects.nonNull(chartResultPkDetailVO.getId())
                        && Objects.equals(chartResultPkDetailVO.getId(), systemChartByCode.getId())) {
                    chartResultPkDetailVO.setIsWorkOrderV2(1);
                    updateFlag = true;
                    break;
                }
            }
            if (updateFlag) {
                leftPojo.setChildList(JSONArray.parseArray(JSON.toJSONString(chartResultPkDetailVOS)));
            }
            break;
        }
    }


    @Override
    public IndexBoardInitVO boardInitApp(IndexBoardInitDTO boardInitDTO) throws XbbException {

        IndexBoardInitVO boardInitAppVO ;

        // 获取用户是否是专注模式
        boolean isFocus = userConfigService.isFocus(boardInitDTO);

        if (isFocus){
            boardInitAppVO = focusBoardInitApp(boardInitDTO);
        }else {
            boardInitAppVO = classicBoardInitApp(boardInitDTO);
        }
        return boardInitAppVO;
    }


    private IndexBoardInitVO classicBoardInitApp(IndexBoardInitDTO boardInitDTO) throws XbbException {

        IndexBoardInitAppVO boardInitAppVO = new IndexBoardInitAppVO();

        String corpid = boardInitDTO.getCorpid();
        String userId = boardInitDTO.getUserId();
        String platform = boardInitDTO.getPlatform();
        UserVO userVO = boardInitDTO.getLoginUser();
        Long homePageId = boardInitDTO.getHomePageId();
        Boolean isCustom = false;
        List<IndexSetDataPojo> setDBList ;
        if (null != homePageId){
            setDBList = systemChartHelp.getCustomConfig(corpid, homePageId, BoardTypeEnum.DINGTALK.getAlias());
            isCustom = true;
        }else {
            setDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.DINGTALK.getCode());
        }

        // 获取公司配置
        List<IndexSetDataPojo> companyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.DINGTALK.getCode());
        // 过虑配置
        List<IndexSetDataPojo> setDataList = checkConfig4Show(companyList, setDBList,corpid,BasicConstant.ONE,isCustom);
        ChartCategoryInitVO companyData = getCompanyData(corpid, userId, platform, setDataList, null);
        // 权限等过滤
        filter(null,companyData,null,corpid,boardInitDTO.getLoginUser(),null,null,setDataList,null,null);

        // 日期相关设置
        setDateRelated(userVO,corpid,userId, boardInitAppVO);

        // 封装展示数据
        List<IndexInitPojo> setList = formatInitApp(boardInitDTO.getLoginUser(), setDataList, companyData, BasicConstant.ZERO,isCustom);

        // pk榜穿透,暂时不用
        leftThroughPK(setList, corpid);

        // 销售简报处理
        JSONObject salesReport = getSalesReport(corpid, userId, setList);
        //判断新工单是否开启应用过滤右侧看板
        checkWorkOrderV2IsUse(corpid,setList);
        boardInitAppVO.setList(setList);
        if (salesReport != null) {
            boardInitAppVO.setSalesReport(salesReport);
        }

        // 访客计划权限处理
        setCommunicatePlanPermission(setList,boardInitAppVO);
        // 图表中心查看权限
        UserVO loginUser = boardInitDTO.getLoginUser();
        Set<String> permSet = loginUser != null ? loginUser.getPermSet() : null;
        boolean hasChartView = Objects.nonNull(permSet) && permSet.contains(ProPermissionAliasEnum.CHART_VIEW.getAlias());
        boardInitAppVO.setChartViewPerm(hasChartView);
        boardInitAppVO.setGroupClose(companyService.flagCloseGroup(corpid,userVO)? 0 : 1);
        return boardInitAppVO;
    }

    private IndexBoardInitVO focusBoardInitApp(IndexBoardInitDTO boardInitDTO) throws XbbException {
        IndexBoardInitAppVO boardInitAppVO = new IndexBoardInitAppVO();
        String corpid = boardInitDTO.getCorpid();
        String userId = boardInitDTO.getUserId();
        String platform = boardInitDTO.getPlatform();
        UserVO userVO = boardInitDTO.getLoginUser();
        Long homePageId = boardInitDTO.getHomePageId();
        Boolean isCustom = false;
        // 获取个人配置
        List<IndexSetDataPojo> focusCategoryDBList;
        List<IndexSetDataPojo> focusWorkDBList;
        if (null != homePageId){
            focusCategoryDBList = systemChartHelp.getCustomConfig(corpid, homePageId, BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getAlias());
            focusWorkDBList = systemChartHelp.getCustomConfig(corpid, homePageId, BoardTypeEnum.FOCUS_DINGTALK_WORK.getAlias());
            isCustom = true;
        }else {
            focusCategoryDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode());
            focusWorkDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.FOCUS_DINGTALK_WORK.getCode());
        }
        // 获取公司配置
        List<IndexSetDataPojo> focusCategoryCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode());
        List<IndexSetDataPojo> focusWorkCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.FOCUS_DINGTALK_WORK.getCode());
        // 过虑配置
        List<IndexSetDataPojo> focusCategorySetDataList = checkConfig4Show(focusCategoryCompanyList, focusCategoryDBList,corpid,BasicConstant.ZERO,isCustom);
        List<IndexSetDataPojo> focusWorkSetDataList = checkConfig4Show(focusWorkCompanyList, focusWorkDBList,corpid,BasicConstant.ONE,isCustom);
        ChartCategoryInitVO companyData = getCompanyData(corpid, userId, platform, focusCategoryDBList, focusWorkDBList);
        // 权限等过滤
        filter(null,null,companyData,corpid,boardInitDTO.getLoginUser(),null,null,null,focusCategorySetDataList,focusWorkSetDataList);
        // 日期相关设置
        setDateRelated(userVO,corpid,userId, boardInitAppVO);
        // 封装展示数据
        List<IndexInitPojo> focusCategorySetList = formatInitApp(boardInitDTO.getLoginUser(), focusCategorySetDataList, companyData, BasicConstant.ZERO,isCustom);
        List<IndexInitPojo> focusWorkSetList = formatInitApp(boardInitDTO.getLoginUser(), focusWorkSetDataList, companyData, BasicConstant.ZERO,isCustom);
        // pk榜穿透,暂时不用
        leftThroughPK(focusCategorySetList, corpid);
        // 销售简报处理
        JSONObject salesReport = getSalesReport(corpid, userId, focusWorkSetList);
        // 公告处理
//        checkAnnouncementPojo(focusRightSetList, corpid);
        // 访客计划权限处理
        setCommunicatePlanPermission(focusWorkSetList,boardInitAppVO);
        //判断新工单是否开启应用过滤右侧看板
        checkWorkOrderV2IsUse(corpid,focusWorkSetList);
        boardInitAppVO.setCategoryList(focusCategorySetList);
        boardInitAppVO.setWorkList(focusWorkSetList);
        if (salesReport != null) {
            boardInitAppVO.setSalesReport(salesReport);
        }
        // 图表中心查看权限
        UserVO loginUser = boardInitDTO.getLoginUser();
        Set<String> permSet = loginUser != null ? loginUser.getPermSet() : null;
        boolean hasChartView = Objects.nonNull(permSet) && permSet.contains(ProPermissionAliasEnum.CHART_VIEW.getAlias());
        boardInitAppVO.setChartViewPerm(hasChartView);
        boardInitAppVO.setGroupClose(companyService.flagCloseGroup(corpid,userVO)? 0 : 1);
        return boardInitAppVO;
    }

    @Override
    public IndexBoardGetConfigVO getConfigWeb(IndexBoardGetConfigDTO getConfigDTO) throws XbbException {
        IndexBoardGetConfigWebVO getConfigWebVO = new IndexBoardGetConfigWebVO();

        String corpid = getConfigDTO.getCorpid();
        String userId = getConfigDTO.getUserId();
        String platform = getConfigDTO.getPlatform();
        UserVO userVO = getConfigDTO.getLoginUser();
        Boolean saveCustomPageFlag = getConfigDTO.getSaveCustomPageFlag();
        Long homePageId = getConfigDTO.getHomePageId();

        // 是否是初始化公司
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("userId", "0");
        param.put("del", DelEnum.NORMAL.getDel());
        Integer count = indexSetModel.getEntitysCount(param);
        // 自定义首页新建
        if (saveCustomPageFlag && null == homePageId){
            count = 0;
        }
        // 该公司是否有经典模式
        boolean hasClassicMode = commonHelp.hasClassicMode(corpid);
        if (hasClassicMode){
            getConfigWebVO.setHasClassicMode(BasicConstant.ONE);
        }else {
            getConfigWebVO.setHasClassicMode(BasicConstant.ZERO);
        }

        // 五个看板的配置
        List<IndexSetDataPojo> leftSetDBList;
        List<IndexSetDataPojo> rightSetDBList;
        List<IndexSetDataPojo> dingTalkSetDBList = null;
        List<IndexSetDataPojo> focusDingTalkCategorySetDBList = null;
        List<IndexSetDataPojo> focusDingTalkWorkSetDBList = null;

        // 管理员自定义首页分配
        JSONObject customIndexSet = null;
        if (null != getConfigDTO.getHomePageId()){
            customIndexSet = getCustomIndexSet(getConfigDTO.getHomePageId(),corpid);
        }
        if (null != customIndexSet){
            leftSetDBList = (List<IndexSetDataPojo>)customIndexSet.get(BoardTypeEnum.WEB_LEFT.getAlias());
            rightSetDBList = (List<IndexSetDataPojo>)customIndexSet.get(BoardTypeEnum.WEB_RIGHT.getAlias());
            dingTalkSetDBList = (List<IndexSetDataPojo>)customIndexSet.get(BoardTypeEnum.DINGTALK.getAlias());
            focusDingTalkCategorySetDBList = (List<IndexSetDataPojo>)customIndexSet.get(BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getAlias());
            focusDingTalkWorkSetDBList=(List<IndexSetDataPojo>)customIndexSet.get(BoardTypeEnum.FOCUS_DINGTALK_WORK.getAlias());
        }else {
            // 获取个人配置
            if (saveCustomPageFlag && null == homePageId){
                // 自定义首页新建
                leftSetDBList = systemChartHelp.getUserConfig(corpid, "0", BoardTypeEnum.WEB_LEFT.getCode());
                rightSetDBList = systemChartHelp.getUserConfig(corpid, "0", BoardTypeEnum.WEB_RIGHT.getCode());
                focusDingTalkCategorySetDBList = systemChartHelp.getUserConfig(corpid, "0", BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode());
                focusDingTalkWorkSetDBList = systemChartHelp.getUserConfig(corpid, "0", BoardTypeEnum.FOCUS_DINGTALK_WORK.getCode());
                if (hasClassicMode){
                    dingTalkSetDBList = systemChartHelp.getUserConfig(corpid, "0", BoardTypeEnum.DINGTALK.getCode());
                }
            }else {
                leftSetDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.WEB_LEFT.getCode());
                rightSetDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.WEB_RIGHT.getCode());
            }
        }
        // 获取公司配置
        List<IndexSetDataPojo> leftCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.WEB_LEFT.getCode());
        List<IndexSetDataPojo> rightCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.WEB_RIGHT.getCode());
        List<IndexSetDataPojo> dingTalkCompanyList = null;
        List<IndexSetDataPojo> focusDingTalkCategoryCompanyList = null;
        List<IndexSetDataPojo> focusDingTalkWorkCompanyList = null;
        // 管理员分配首页，编辑模式下才有
        if (null != dingTalkSetDBList){
            dingTalkCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.DINGTALK.getCode());
            focusDingTalkCategoryCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode());
            focusDingTalkWorkCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.FOCUS_DINGTALK_WORK.getCode());
        }
        // 过虑配置
        Boolean isCustom = null != saveCustomPageFlag && saveCustomPageFlag;
        List<IndexSetDataPojo> leftSetDataList = checkConfig4Save(leftCompanyList, leftSetDBList,isCustom);
        List<IndexSetDataPojo> rightSetDataList = checkConfig4Save(rightCompanyList, rightSetDBList,isCustom);
        List<IndexSetDataPojo> dingTalkSetDataList = null;
        List<IndexSetDataPojo> focusDingTalkCategorySetDataList = null;
        List<IndexSetDataPojo> focusDingTalkWorkSetDataList = null;
        if (null != dingTalkSetDBList){
            dingTalkSetDataList = checkConfig4Save(dingTalkCompanyList, dingTalkSetDBList,isCustom);
        }
        if (null != focusDingTalkCategorySetDBList){
            focusDingTalkCategorySetDataList = checkConfig4Save(focusDingTalkCategoryCompanyList, focusDingTalkCategorySetDBList,isCustom);
        }
        if (null != focusDingTalkWorkSetDBList){
            focusDingTalkWorkSetDataList = checkConfig4Save(focusDingTalkWorkCompanyList, focusDingTalkWorkSetDBList,isCustom);
        }

        // 获取当前数据
        ChartCategoryInitVO companyData = getCompanyData(corpid, userId, platform, leftSetDataList, rightSetDataList);
        ChartCategoryInitVO dingTalkCompanyData = null;
        if (null != dingTalkSetDBList){
            dingTalkCompanyData = getCompanyData(corpid, userId, PlatFormEnum.DINGTALK.getValue(), dingTalkSetDataList, null);
        }
        ChartCategoryInitVO focusDingTalkCompanyData = null;
        if (null != focusDingTalkCategorySetDBList || null != focusDingTalkWorkSetDataList){
            focusDingTalkCompanyData = getCompanyData(corpid, userId, PlatFormEnum.DINGTALK.getValue(), focusDingTalkCategorySetDataList, focusDingTalkWorkSetDataList);
            formatCompanyData(getConfigDTO.getLoginUser(), focusDingTalkCompanyData);
        }

        // 权限等过滤
        filter(companyData,dingTalkCompanyData,focusDingTalkCompanyData,corpid,getConfigDTO.getLoginUser(), leftSetDataList, rightSetDataList, dingTalkSetDataList, focusDingTalkCategorySetDataList, focusDingTalkWorkSetDataList);

        // 日期相关设置
        setDateRelated(userVO,corpid,userId, getConfigWebVO);

        // 封装展示数据
        List<IndexInitPojo> leftList = formatInitWeb(getConfigDTO.getLoginUser(), leftSetDataList, companyData, count, BasicConstant.ZERO,isCustom);
        List<IndexInitPojo> rightList = formatInitWeb(getConfigDTO.getLoginUser(), rightSetDataList, companyData, count, BasicConstant.ONE,isCustom);
        List<IndexInitPojo> dingTalkList = null;
        List<IndexInitPojo> focusDingTalkCategoryList = null;
        List<IndexInitPojo> focusDingTalkWorkList = null;
        if (null != dingTalkSetDBList){
            dingTalkList = formatInitApp(getConfigDTO.getLoginUser(), dingTalkSetDataList, dingTalkCompanyData, BasicConstant.ZERO,isCustom);
        }
        if (null != focusDingTalkCategorySetDBList){
            focusDingTalkCategoryList = formatInitApp(getConfigDTO.getLoginUser(), focusDingTalkCategorySetDataList, focusDingTalkCompanyData, BasicConstant.ZERO,isCustom);
            // 将访客计划首页看板隐藏
            setCommunicatePlanHidden(focusDingTalkCategoryList,PaasConstant.ENABLE_HIDDEN);
        }
        if (null != focusDingTalkWorkSetDBList){
            focusDingTalkWorkList = formatInitApp(getConfigDTO.getLoginUser(), focusDingTalkWorkSetDataList, focusDingTalkCompanyData, BasicConstant.ONE,isCustom);
        }
        //判断首页右侧看板，攻略卡片是否开启
//        checkRaiders(rightList, corpid);

        getConfigWebVO.setLeftList(leftList);
        getConfigWebVO.setRightList(rightList);
        getConfigWebVO.setDingTalkList(dingTalkList);
        getConfigWebVO.setFocusDingTalkCategoryList(focusDingTalkCategoryList);
        getConfigWebVO.setFocusDingTalkWorkList(focusDingTalkWorkList);

        return getConfigWebVO;
    }

    @Override
    public IndexBoardGetConfigVO getConfigApp(IndexBoardGetConfigDTO getConfigDTO) throws XbbException {
        IndexBoardGetConfigAppVO getConfigAppVO;
        // 获取用户是否是专注模式
        boolean isFocus = userConfigService.isFocus(getConfigDTO);
        if (isFocus){
            getConfigAppVO = getFocusConfigApp(getConfigDTO);
        }else {
            getConfigAppVO = getClassicConfigApp(getConfigDTO);
        }
        return getConfigAppVO;
    }

    @Override
    public IndexBoardSaveConfigVO saveConfigWeb(IndexBoardSaveConfigDTO saveConfigDTO) throws XbbException {
        IndexBoardSaveConfigVO saveConfigVO = new IndexBoardSaveConfigVO();
        IndexBoardSaveConfigWebDTO saveConfigWebDTO;
        if (saveConfigDTO instanceof IndexBoardSaveConfigWebDTO){
            saveConfigWebDTO = (IndexBoardSaveConfigWebDTO) saveConfigDTO;
        }else {
            // todo 传参错误
            return saveConfigVO;
        }
        String corpid = saveConfigWebDTO.getCorpid();
        String userId = saveConfigWebDTO.getUserId();
        String platform = saveConfigWebDTO.getPlatform();
        Integer customPageFlag = saveConfigWebDTO.getCustomPageFlag();
        JSONObject refIds = saveConfigWebDTO.getRefIds();
        refIds = null == refIds ? new JSONObject() : refIds;

        List<IndexBoardSaveItemPojo> leftBoard = saveConfigWebDTO.getLeftBoard();
        List<IndexBoardSaveItemPojo> rightBoard = saveConfigWebDTO.getRightBoard();
        List<IndexBoardSaveItemPojo> dingTalkBoard = saveConfigWebDTO.getDingTalkBoard();
        if (leftBoard == null || leftBoard.size() == 0) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.ENABLED_BOARD_CANNOT_EMPTY);
        }
        if (leftBoard.size() > WEB_LEFT_BOARD_COUNT) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.ENABLED__BOARDS_CANNOT_EXCEED, WEB_LEFT_BOARD_COUNT);
        }

        // TODO 获取当前数据(角色修改后期考虑)
        ChartCategoryInitVO companyData = getCompanyData(corpid, userId, platform);
        formatCompanyData(saveConfigWebDTO.getLoginUser(), companyData);
        List<ChartCategoryEntity> categoryList = companyData.getCategoryList();
        List<ChartEntity> chartList = companyData.getChartList();

        HashMap<Long, String> categoryListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        categoryList.forEach(category -> categoryListMap.put(category.getId(), category.getName()));
        chartList.forEach(chart -> categoryListMap.put(chart.getId(), chart.getName()));

        List<Long> saveCategoryIds = new ArrayList<>();
        List<Long> saveChartIds = new ArrayList<>();
        getConfigSaveIds(saveCategoryIds, saveChartIds, leftBoard);
        getConfigSaveIds(saveCategoryIds, saveChartIds, rightBoard);
        //把获取到的分类、图表封装塞入 companyData 内的对应map
        formatCompanyData(saveConfigWebDTO.getLoginUser(), companyData);

        for (Long id : saveCategoryIds) {
            if (!companyData.getCategoryMap().containsKey(id)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.BOARD_NOT_EXIST);
            }
        }
        for (Long id : saveChartIds) {
            if (!companyData.getSystemChartMap().containsKey(id) && !companyData.getCustomChartMap().containsKey(id)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.BOARD_NOT_EXIST);
            }
        }

        // 获取个人配置
        Map<String,IndexSetEntity> indexSetEntityMap = packageSetEntity(customPageFlag,refIds,corpid,userId);
        IndexSetEntity leftSetEntity = indexSetEntityMap.get(BoardTypeEnum.WEB_LEFT.getAlias());
        IndexSetEntity rightSetEntity = indexSetEntityMap.get(BoardTypeEnum.WEB_RIGHT.getAlias());

        List<IndexSetDataPojo> leftSetDBList = leftSetEntity.getContentData().toJavaList(IndexSetDataPojo.class);
        List<IndexSetDataPojo> rightSetDBList = rightSetEntity.getContentData().toJavaList(IndexSetDataPojo.class);

        // 获取公司配置
        List<IndexSetDataPojo> leftCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.WEB_LEFT.getCode());
        List<IndexSetDataPojo> rightCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.WEB_RIGHT.getCode());
        // 过虑配置(数据库中所有启用，关闭集合)
        Boolean isCustom = Objects.equals(customPageFlag, HomePageCustomTypeEnum.IS_CUSTOM.getCode());
        List<IndexSetDataPojo> leftSetDataList = checkConfig4Save(leftCompanyList, leftSetDBList,isCustom);
        List<IndexSetDataPojo> rightSetDataList = checkConfig4Save(rightCompanyList, rightSetDBList,isCustom);

        // 原先看板ID
        List<Long> oldLeftEnableDataId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        leftSetDataList.forEach(item -> {
            if(Objects.equals(item.getEnable(), 1)){
                oldLeftEnableDataId.add(item.getChartCategoryId());
            }
        });

        List<Long> oldRightEnableDataId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        rightSetDataList.forEach(item -> {
            if(Objects.equals(item.getEnable(), 1)){
                oldRightEnableDataId.add(item.getChartCategoryId());
            }
        });

        // 未启用看板后端处理
        List<IndexSetDataPojo> leftDisableList = getDisableBoardList(leftSetDataList, leftBoard);
        List<IndexSetDataPojo> rightDisableList = getDisableBoardList(rightSetDataList, rightBoard);


        // 数据
        List<IndexSetDataPojo> leftSaveData = getEnableConfig(leftSetDataList, leftBoard, companyData);
        leftSaveData.addAll(leftDisableList);
        List<IndexSetDataPojo> rightSaveData = getEnableConfig(rightSetDataList, rightBoard, companyData);
        rightSaveData.addAll(rightDisableList);

        // 保存配置
        JSONArray leftData = new JSONArray();
        leftData.addAll(leftSaveData);
        leftSetEntity.setContentData(leftData);
        try {
            indexSetModel.save(leftSetEntity);
        } catch (Exception e) {
            LOG.error("保存首页看板公司配置失败",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        // 管理员分配自定义自定义首页不用日志
        if (Objects.equals(customPageFlag,HomePageCustomTypeEnum.IS_CUSTOM.getCode())){
            JSONArray rightData = new JSONArray();
            rightData.addAll(rightSaveData);
            rightSetEntity.setContentData(rightData);
            try {
                indexSetModel.save(rightSetEntity);
            } catch (Exception e) {
                LOG.error("保存首页看板公司配置失败",e);
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            // 更新app首页顺序
            IndexBoardSaveConfigAppDTO saveConfigAppDTO = new IndexBoardSaveConfigAppDTO();
            saveConfigAppDTO.setEnableList(dingTalkBoard);
            saveConfigAppDTO.setCustomPageFlag(customPageFlag);
            saveConfigAppDTO.setRefIds(refIds);
            saveConfigAppDTO.setCorpid(corpid);
            saveConfigAppDTO.setUserId(userId);
            saveConfigAppDTO.setPlatform(platform);
            saveConfigAppDTO.setLoginUser(saveConfigWebDTO.getLoginUser());
            saveConfigAppDTO.setCategoryEnableList(saveConfigWebDTO.getFocusDingTalkCategoryBoard());
            saveConfigAppDTO.setWorkEnableList(saveConfigWebDTO.getFocusDingTalkWorkBoard());
            IndexBoardSaveConfigVO appSaveConfigVO = saveConfigApp(saveConfigAppDTO);
            HomePageManageSaveDTO homePageManageSaveDTO = saveConfigWebDTO.getHomePageManageSaveDTO();
            homePageManageSaveDTO.setCorpid(corpid);
            homePageManageSaveDTO.setUserId(userId);
            homePageManageSaveDTO.setLoginUser(saveConfigDTO.getLoginUser());
            homePageManageSaveDTO.setLoginUserName(saveConfigDTO.getLoginUserName());
            if (null == homePageManageSaveDTO){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, SystemErrorCodeEnum.API_ERROR_100028.getMsg());
            }
            if (null == homePageManageSaveDTO.getId()){
                // 新建
                JSONObject tempRefIds = appSaveConfigVO.getRefIds();
                if (null != tempRefIds){
                    refIds = tempRefIds;
                }
                refIds.put(BoardTypeEnum.WEB_LEFT.getAlias(),leftSetEntity.getId());
                refIds.put(BoardTypeEnum.WEB_RIGHT.getAlias(),rightSetEntity.getId());
                homePageManageSaveDTO.setRefIds(refIds);
            }
            // 更新自定义首页表
            homePageManageService.save(homePageManageSaveDTO);
            return saveConfigVO;
        }

        List<Long> newSystemIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        leftBoard.forEach(item -> newSystemIds.add(item.getChartCategoryId()));
        List<Long> newOldLeftEnableDataId = new ArrayList<>(oldLeftEnableDataId);
        // 利用差集，配置内容比较：A:1,2,3,4  B1:1,2,3,4,5  B2:1,3,4  B3:1,2,5
        oldLeftEnableDataId.removeAll(newSystemIds);
        newSystemIds.removeAll(newOldLeftEnableDataId);

        String loginUserName = saveConfigWebDTO.getLoginUserName();
        String memo;
        List<String> updataNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        oldLeftEnableDataId.forEach(dataId -> updataNameList.add(categoryListMap.get(dataId)));
        String updataItem = StringUtils.join(updataNameList, "，");

        List<String> leftNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        newSystemIds.forEach(leftId -> leftNameList.add(categoryListMap.get(leftId)));
        String enableItem = StringUtils.join(leftNameList, "，");

        // 例：A:1,2,3,4  B1:1,2,3,4,5 说明没有关闭任何看板
        if(Objects.equals(oldLeftEnableDataId.size(), 0)){
            if(newSystemIds.size() > 1){
                // 例：B1:1,2,3,4,5  A:1,2,3,4 说明只是开启了看板
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_HOME_BOARD), loginUserName, newSystemIds.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(OperateTypeEnum.ENABLE.getName());
                infoArrPojo.setContent(enableItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                        "", "", memo, saveConfigWebDTO.getHttpHeader());
            } else if(Objects.equals(newSystemIds.size(), 1)){
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_HOME_BOARD), loginUserName, OperateTypeEnum.ENABLE.getName(), enableItem);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                        newSystemIds.get(0).toString(), enableItem, memo, saveConfigWebDTO.getHttpHeader());
            }
        } else {
            // 例：A:1,2,3,4  (B2:1,3,4 或 B3:1,2,5) 说明关闭或并开启任何看板
            if(newSystemIds.size() > 0){
                // 例：A:1,2,3,4  B3:1,2,5  开启5，关闭3,4
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_HOME_BOARD), loginUserName, newSystemIds.size() + oldLeftEnableDataId.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTab(OperateTypeEnum.ENABLE.getName());
                infoArrPojo.setTitle(OperateTypeEnum.ENABLE.getName());
                infoArrPojo.setContent(enableItem);
                infoArrPojoList.add(infoArrPojo);

                InfoArrPojo arrPojo = new InfoArrPojo();
                arrPojo.setTab(OperateTypeEnum.CLOSE.getName());
                arrPojo.setTitle(OperateTypeEnum.CLOSE.getName());
                arrPojo.setContent(updataItem);
                infoArrPojoList.add(arrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                        "", "", memo, saveConfigWebDTO.getHttpHeader());
            } else {
                // 例：A:1,2,3,4  B2:1,3,4 说明只是关闭了看板
                if(oldLeftEnableDataId.size() > 1){
                    // 例：B1:1,2,3,4,5  A:1,2,3,4 说明只是开启了看板
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_HOME_BOARD), loginUserName, oldLeftEnableDataId.size());
                    List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    InfoArrPojo infoArrPojo = new InfoArrPojo();
                    infoArrPojo.setTitle(OperateTypeEnum.CLOSE.getName());
                    infoArrPojo.setContent(updataItem);
                    infoArrPojoList.add(infoArrPojo);
                    mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                            "", "", memo, saveConfigWebDTO.getHttpHeader());
                } else if(Objects.equals(oldLeftEnableDataId.size(), 1)){
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_HOME_BOARD), loginUserName, OperateTypeEnum.CLOSE.getName(), updataItem);
                    mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                            oldLeftEnableDataId.get(0).toString(), updataItem, memo, saveConfigWebDTO.getHttpHeader());
                }
            }
        }

        JSONArray rightData = new JSONArray();
        rightData.addAll(rightSaveData);
        rightSetEntity.setContentData(rightData);
        try {
            indexSetModel.save(rightSetEntity);
        } catch (Exception e) {
            LOG.error("保存首页看板公司配置失败",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }


        List<Long> newCustomIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        rightBoard.forEach(item -> newCustomIds.add(item.getChartCategoryId()));
        List<Long> newOldRightEnableDataId = new ArrayList<>(oldRightEnableDataId);
        // 利用差集，配置内容比较：A:1,2,3,4  B1:1,2,3,4,5  B2:1,3,4  B3:1,2,5
        oldRightEnableDataId.removeAll(newCustomIds);
        newCustomIds.removeAll(newOldRightEnableDataId);

        List<String> rightUpdataNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        oldRightEnableDataId.forEach(dataId -> rightUpdataNameList.add(categoryListMap.get(dataId)));
        String rightUpdataItem = StringUtils.join(rightUpdataNameList, "，");

        List<String> rightNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        newCustomIds.forEach(leftId -> rightNameList.add(categoryListMap.get(leftId)));
        String rightEnableItem = StringUtils.join(rightNameList, "，");

        // 例：A:1,2,3,4  B1:1,2,3,4,5 说明没有关闭任何看板
        if(Objects.equals(oldRightEnableDataId.size(), 0)){
            if(newCustomIds.size() > 1){
                // 例：B1:1,2,3,4,5  A:1,2,3,4 说明只是开启了看板
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_HOME_BOARD), loginUserName, newCustomIds.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(OperateTypeEnum.ENABLE.getName());
                infoArrPojo.setContent(rightEnableItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                        "", "", memo, saveConfigWebDTO.getHttpHeader());
            } else if(Objects.equals(newCustomIds.size(), 1)){
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_HOME_BOARD), loginUserName, OperateTypeEnum.ENABLE.getName(), rightEnableItem);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                        newCustomIds.get(0).toString(), rightEnableItem, memo, saveConfigWebDTO.getHttpHeader());
            }
        } else {
            // 例：A:1,2,3,4  (B2:1,3,4 或 B3:1,2,5) 说明关闭或并开启任何看板
            if(newCustomIds.size() > 0){
                // 例：A:1,2,3,4  B3:1,2,5  开启5，关闭3,4
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_HOME_BOARD), loginUserName, newCustomIds.size() + oldRightEnableDataId.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTab(OperateTypeEnum.ENABLE.getName());
                infoArrPojo.setTitle(OperateTypeEnum.ENABLE.getName());
                infoArrPojo.setContent(rightEnableItem);
                infoArrPojoList.add(infoArrPojo);

                InfoArrPojo arrPojo = new InfoArrPojo();
                arrPojo.setTab(OperateTypeEnum.CLOSE.getName());
                arrPojo.setTitle(OperateTypeEnum.CLOSE.getName());
                arrPojo.setContent(rightUpdataItem);
                infoArrPojoList.add(arrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                        "", "", memo, saveConfigWebDTO.getHttpHeader());
            } else {
                // 例：A:1,2,3,4  B2:1,3,4 说明只是关闭了看板
                if(oldRightEnableDataId.size() > 1){
                    // 例：B1:1,2,3,4,5  A:1,2,3,4 说明只是开启了看板
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_HOME_BOARD), loginUserName, oldRightEnableDataId.size());
                    List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    InfoArrPojo infoArrPojo = new InfoArrPojo();
                    infoArrPojo.setTitle(OperateTypeEnum.CLOSE.getName());
                    infoArrPojo.setContent(rightUpdataItem);
                    infoArrPojoList.add(infoArrPojo);
                    mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                            "", "", memo, saveConfigWebDTO.getHttpHeader());
                } else if(Objects.equals(oldRightEnableDataId.size(), 1)){
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_HOME_BOARD), loginUserName, OperateTypeEnum.CLOSE.getName(), rightUpdataItem);
                    mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                            oldRightEnableDataId.get(0).toString(), rightUpdataItem, memo, saveConfigWebDTO.getHttpHeader());
                }
            }
        }

        return saveConfigVO;
    }

    @Override
    public IndexBoardSaveConfigVO saveConfigApp(IndexBoardSaveConfigDTO saveConfigDTO) throws XbbException {
        IndexBoardSaveConfigVO saveConfigVO = new IndexBoardSaveConfigVO();

        IndexBoardSaveConfigAppDTO saveConfigAppDTO;
        if (saveConfigDTO instanceof IndexBoardSaveConfigAppDTO){
            saveConfigAppDTO = (IndexBoardSaveConfigAppDTO) saveConfigDTO;
        }else {
            // todo 传参错误
            return saveConfigVO;
        }
        String corpid = saveConfigAppDTO.getCorpid();
        String userId = saveConfigAppDTO.getUserId();
        String platform = saveConfigAppDTO.getPlatform();
        Integer customPageFlag = saveConfigAppDTO.getCustomPageFlag();
        JSONObject refIds = saveConfigAppDTO.getRefIds();

        // 获取公司是否有经典模式
        boolean hasClassicMode = commonHelp.hasClassicMode(corpid);

        // 获取用户是否是专注模式
        boolean isFocus = true;
        if (hasClassicMode){
            isFocus = userConfigService.isFocus(saveConfigAppDTO);
        }
        List<IndexBoardSaveItemPojo> enableList = saveConfigAppDTO.getEnableList();
        List<IndexBoardSaveItemPojo> focusCategoryEnableList = saveConfigAppDTO.getCategoryEnableList();
        List<IndexBoardSaveItemPojo> focusWorkEnableList = saveConfigAppDTO.getWorkEnableList();

        // TODO 获取当前数据(角色修改后期考虑)
        ChartCategoryInitVO companyData = getCompanyData(corpid, userId, platform);
        formatCompanyData(saveConfigAppDTO.getLoginUser(), companyData);
        // 如果是管理中心-首页管理新建或者编辑
        if (Objects.equals(customPageFlag,HomePageCustomTypeEnum.IS_CUSTOM.getCode())){
            // 公司是否有经典模式，如果有需要新建或者更新移动端的经典模式和专注模式，没有则只需要更新专注模式
            JSONObject classicRefIds = new JSONObject();
            if (hasClassicMode){
                // 更新经典看板
                classicRefIds = saveClassicConfigApp(saveConfigAppDTO,companyData,enableList,refIds);
            }
            // 更新专注模式下的两种app看板
            JSONObject focusRefIds = saveFocusConfigApp(saveConfigAppDTO,companyData,focusCategoryEnableList,focusWorkEnableList,refIds);
            focusRefIds.putAll(classicRefIds);
            saveConfigVO.setRefIds(focusRefIds);
        }else {
            // 是否是专注模式，如果是专注模式，更新专注模式下的看板，否则判断公司是否有经典看板，没有则报错，否则更新经典看板
            if (isFocus){
                // 更新专注模式下的两种app看板
                saveFocusConfigApp(saveConfigAppDTO,companyData,focusCategoryEnableList,focusWorkEnableList,refIds);
            }else {
                if (hasClassicMode){
                    // 更新经典看板
                    saveClassicConfigApp(saveConfigAppDTO,companyData,enableList,refIds);
                }else {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
                }
            }
        }

        return saveConfigVO;
    }

    @Override
    public IndexBoardChartGetConfigVO chartGetConfig(IndexBoardChartGetConfigDTO chartGetConfigDTO) throws XbbException {
        IndexBoardChartGetConfigVO chartGetConfigVO = new IndexBoardChartGetConfigVO();

        String corpid = chartGetConfigDTO.getCorpid();
        String userId = chartGetConfigDTO.getUserId();
        String platform = chartGetConfigDTO.getPlatform();
        Long homePageId = chartGetConfigDTO.getHomePageId();

        // 参数
        Long chartCategoryId = chartGetConfigDTO.getChartCategoryId();
        // 看板类型（web左侧，web右侧，app)
        Integer boardType;
        // 是否是专注模式
        if (StringConstant.PLATFORM_DINGTALK.equals(platform)){
            if (userConfigService.isFocus(chartGetConfigDTO)){
                boardType = BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode();
            }else {
                boardType = BoardTypeEnum.DINGTALK.getCode();
            }
        }else {
            boardType = BoardTypeEnum.WEB_LEFT.getCode();
        }

        ChartCategoryEntity categoryEntity = chartCategoryModel.getByKey(chartCategoryId, corpid);
        if (categoryEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.BOARD_NOT_EXIST_OR_DELETED);
        }

        // 机会历史bug兼容
        Map<String, ChartEntity> funnelCommonMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 获取当前看板实体
        IndexSetDataPojo setDataPojo = systemChartHelp.getSetDataPojo(corpid, userId, platform, boardType, chartCategoryId,homePageId);
        // 获取当前指标数据
        List<ChartEntity> chartList = getChartListByCategoryId(corpid, chartCategoryId, null);
        // chartMap
        Map<Long, ChartEntity> systemChartMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, ChartEntity> customChartMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 是否有展示方式筛选项
        boolean showFlag = false;
        for (ChartEntity entity : chartList) {
            if (!showFlag) {
                showFlag = hasShowTypes(entity.getShowTypes());
            }
            if (Objects.equals(StatisticsTypeEnum.CUSTOM_STATISTIC.getCode(), entity.getStatisticsType())) {
                customChartMap.put(entity.getId(), entity);
            } else {
                systemChartMap.put(entity.getId(), entity);
            }
            if(Objects.equals(ChartTypeEnum.FUNNEL_COMMON.getCode(),entity.getChartType())) {
                funnelCommonMap.put(String.format(SymbolConstant.UNDERLINE, entity.getStatisticsType(),entity.getId()), entity);
            }
        }
        // 获取展示方式数组
        List<KeyValuePojo> showTypeArr = getShowTypeList(platform, showFlag);
        // 销售机会不设置展示展示
        if(Objects.equals(ChartCategoryAliasEnum.OPPORTUNITY.getAlias(), categoryEntity.getAlias())) {
            showTypeArr = new ArrayList<>();
            setDataPojo.setShowType(ChartTypeEnum.FUNNEL_COMMON.getCode());
            List<IndexBoardChartSavePojo> oppEnableList = setDataPojo.getEnableList();
            List<IndexBoardChartSavePojo> oppDisableList = setDataPojo.getDisableList();
            int sort = oppEnableList != null ? oppEnableList.size() : 1;
            sort += funnelCommonMap.size();

            // 需要调整销售漏斗的顺序为第一位
            boolean changeSort = true;
            if(oppEnableList != null && !oppEnableList.isEmpty()) {
                IndexBoardChartSavePojo oppEnablePojo = oppEnableList.get(0);
                if(funnelCommonMap.containsKey(String.format(SymbolConstant.UNDERLINE, oppEnablePojo.getStatisticsType(), oppEnablePojo.getId()))) {
                    changeSort = false;
                }
            }

            if(oppEnableList != null && changeSort) {
                // 先移除要添加的数据
                Iterator<IndexBoardChartSavePojo> iterator1 = oppEnableList.iterator();
                while (iterator1.hasNext()) {
                    IndexBoardChartSavePojo pojo = iterator1.next();
                    if(funnelCommonMap.containsKey(String.format(SymbolConstant.UNDERLINE, pojo.getStatisticsType(), pojo.getId()))) {
                        iterator1.remove();
                    }
                }
                Iterator<IndexBoardChartSavePojo> iterator2 = oppDisableList.iterator();
                while (iterator2.hasNext()) {
                    IndexBoardChartSavePojo pojo = iterator2.next();
                    if(funnelCommonMap.containsKey(String.format(SymbolConstant.UNDERLINE, pojo.getStatisticsType(), pojo.getId()))) {
                        iterator2.remove();
                    }
                }
                // 添加销售漏斗数
                for(ChartEntity entity : funnelCommonMap.values()) {
                    IndexBoardChartSavePojo pojo = new IndexBoardChartSavePojo();
                    pojo.setId(entity.getId());
                    pojo.setSort(sort + 1);
                    pojo.setStatisticsType(entity.getStatisticsType());
                    oppEnableList.add(pojo);
                    sort --;
                }
                setDataPojo.setEnableList(oppEnableList);
            }
        }
        // 已启用指标
        List<IndexBoardChartPojo> enableList = getEnableChartList(setDataPojo.getEnableList(), chartList);
        // 未启用指标
        List<IndexBoardChartPojo> disbaleList = getDisableChartList(chartList);
        // TODO 过滤权限相关
        Set<Long> depIdIn = chartPermissionHelp.getAllDeptIds(chartGetConfigDTO.getLoginUser());
        boolean dingac870976e8f8af4d = Objects.equals("dingac870976e8f8af4d", corpid) && Objects.equals("6605336336699541", userId);
        if (dingac870976e8f8af4d) {
            LOG.info("hongxiao--start--:" + JSON.toJSONString(systemChartMap) + "    enableList:" + JSON.toJSONString(enableList) + "    disbaleList:" + JSON.toJSONString(disbaleList) + "    saasPermissions:" + JSON.toJSONString(chartGetConfigDTO.getLoginUser().getPermSet()));
        }
        checkPermission4ConfigChart(chartGetConfigDTO.getLoginUser(), depIdIn, enableList, disbaleList, systemChartMap, customChartMap);
        if (dingac870976e8f8af4d) {
            LOG.info("hongxiao--end--:" + JSON.toJSONString(disbaleList));
        }

        // 超过12个的，显示到未启用列表
        if (enableList.size() > CHART_MAX_COUNT) {
            List<IndexBoardChartPojo> overList = enableList.subList(CHART_MAX_COUNT, enableList.size());
            enableList = enableList.subList(0, CHART_MAX_COUNT);
            disbaleList.addAll(overList);
        }

        chartGetConfigVO.setChartCategoryId(chartCategoryId);
        chartGetConfigVO.setChartCategoryType(ChartConstant.CHART_CATEGORY_TYPE_CATEGORY);
        chartGetConfigVO.setName(categoryEntity.getName());
        chartGetConfigVO.setShowType(setDataPojo.getShowType());
        chartGetConfigVO.setShowTypeArr(showTypeArr);
        chartGetConfigVO.setEnableList(enableList);
        chartGetConfigVO.setDisableList(disbaleList);

        return chartGetConfigVO;
    }

    @Override
    public IndexBoardChartSaveConfigVO chartSaveConfig(IndexBoardChartSaveConfigDTO chartSaveConfigDTO) throws XbbException {
        IndexBoardChartSaveConfigVO chartSaveConfigVO = new IndexBoardChartSaveConfigVO();

        String corpid = chartSaveConfigDTO.getCorpid();
        String userId = chartSaveConfigDTO.getUserId();
        String platform = chartSaveConfigDTO.getPlatform();
        Long homePageId = chartSaveConfigDTO.getHomePageId();

        // 验证参数
        checkChartSave(chartSaveConfigDTO);

        // 参数
        Long chartCategoryId = chartSaveConfigDTO.getChartCategoryId();
        List<IndexBoardChartSavePojo> disableList = chartSaveConfigDTO.getDisableList();
        if (disableList == null) {
            disableList = new ArrayList<>();
        }

        Integer boardType;
        // 是否是专注模式
        if (StringConstant.PLATFORM_DINGTALK.equals(platform)){
            if (userConfigService.isFocus(chartSaveConfigDTO)){
                boardType = BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode();
            }else {
                boardType = BoardTypeEnum.DINGTALK.getCode();
            }
        }else {
            boardType = BoardTypeEnum.WEB_LEFT.getCode();
        }
        // 获取配置
        IndexSetEntity setEntity;
        if (null != homePageId){
            setEntity = getSetEntity(homePageId,corpid,boardType);
        }else {
            setEntity = getSetEntity(corpid, userId, platform, boardType);
        }
        List<IndexSetDataPojo> setDBList = setEntity.getContentData().toJavaList(IndexSetDataPojo.class);

        // 获取当前看板模块
        IndexSetDataPojo setDataPojo = null;
        for (IndexSetDataPojo dataPojo : setDBList) {
            if (chartCategoryId.equals(dataPojo.getChartCategoryId()) && ChartConstant.CHART_CATEGORY_TYPE_CATEGORY == (dataPojo.getChartCategoryType())) {
                setDataPojo = new IndexSetDataPojo();
                BeanUtil.copyProperties(dataPojo, setDataPojo);
                break;
            }
        }
        // 个人配置不存在，从公司配置里获取
        if(setDataPojo == null) {
            List<IndexSetDataPojo> companyDBList = systemChartHelp.getCompanyConfig(corpid, userId, platform, boardType);
            for (IndexSetDataPojo dataPojo : companyDBList) {
                if (chartCategoryId.equals(dataPojo.getChartCategoryId()) && ChartConstant.CHART_CATEGORY_TYPE_CATEGORY == (dataPojo.getChartCategoryType())) {
                    setDataPojo = new IndexSetDataPojo();
                    BeanUtil.copyProperties(dataPojo, setDataPojo);
                    break;
                }
            }

            if (setDataPojo == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.CANNOT_FIND_SET_BOARD);
            }
            // 添加到个人配置中
            setDBList.add(setDataPojo);
        }

        for (IndexSetDataPojo dataPojo : setDBList) {
            if (chartCategoryId.equals(dataPojo.getChartCategoryId()) && ChartConstant.CHART_CATEGORY_TYPE_CATEGORY == (dataPojo.getChartCategoryType())) {
                dataPojo.setShowType(chartSaveConfigDTO.getShowType());
                dataPojo.setDisableList(disableList);
                dataPojo.setEnableList(chartSaveConfigDTO.getEnableList());
                break;
            }
        }
        JSONArray setData = new JSONArray();
        setData.addAll(setDBList);
        setEntity.setContentData(setData);
        try {
            indexSetModel.save(setEntity);
        } catch (Exception e) {
            LOG.error("保存首页看板配置失败====", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return chartSaveConfigVO;
    }

    @Override
    public IndexBoardHideVO boardHide(IndexBoardHideDTO boardHideDTO) throws XbbException {
        IndexBoardHideVO boardHideVO = new IndexBoardHideVO();

        String corpid = boardHideDTO.getCorpid();
        String userId = boardHideDTO.getUserId();
        String platform = boardHideDTO.getPlatform();

        // 参数
        Long chartCategoryId = boardHideDTO.getChartCategoryId();
        Integer chartCategoryType = boardHideDTO.getChartCategoryType();
        Integer boardType = boardHideDTO.getBoardType();
        // 只可关闭（公告，销售简报）
        ChartCategoryEntity categoryEntity = chartCategoryModel.getByKey(chartCategoryId, corpid);
        if (categoryEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.HOME_BOARD_CATEGORY_NOT_EXIST_OR_DELETED);
        }

        BoardTypeEnum boardTypeEnum = BoardTypeEnum.getByCode(boardType);
        if (boardTypeEnum == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.HOME_BOARD_TYPE_NOT_EMPTY);
        }

        // 获取配置
        IndexSetEntity setEntity = getSetEntity(corpid, userId, platform, boardType);
        List<IndexSetDataPojo> setDBList = setEntity.getContentData().toJavaList(IndexSetDataPojo.class);
        for (IndexSetDataPojo dataPojo : setDBList) {
            if (chartCategoryId.equals(dataPojo.getChartCategoryId()) && chartCategoryType.equals(dataPojo.getChartCategoryType())) {
                dataPojo.setEnable(BasicConstant.NO_USE);
                break;
            }
        }

        JSONArray setData = new JSONArray();
        setData.addAll(setDBList);
        setEntity.setContentData(setData);
        try {
            indexSetModel.save(setEntity);
        } catch (Exception e) {
            LOG.error("隐藏首页看板配置失败",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return boardHideVO;
    }

    @Override
    public IndexSaveFilterVO saveFilter(IndexSaveFilterDTO saveFilterDTO) throws XbbException {
        IndexSaveFilterVO saveFilterVO = new IndexSaveFilterVO();

        String corpid = saveFilterDTO.getCorpid();
        String userId = saveFilterDTO.getUserId();

        // 参数验证
        Integer companyStructType = saveFilterDTO.getCompanyStructType();
        CompanyStructTypeEnum structTypeEnum = CompanyStructTypeEnum.getByCode(companyStructType);
        if (structTypeEnum == CompanyStructTypeEnum.UNKNOWN) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.ORGANIZATION_STRUCTURE_TYPE_ERROR);
        }

        if (structTypeEnum == CompanyStructTypeEnum.DEPARTMENT && saveFilterDTO.getCheckedDepId() == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.FILTER_DEPARTMENT_CANNOT_EMPTY);
        } else if (structTypeEnum == CompanyStructTypeEnum.USER && StringUtil.isEmpty(saveFilterDTO.getCheckedUserId())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.FILTER_EMPLOYEES_CANNOT_EMPTY);
        }

        // 时间参数验证
        checkTime(saveFilterDTO);

        // 保存数据
        IndexFilterDataPojo filterDataPojo = new IndexFilterDataPojo();
        BeanUtil.copyProperties(saveFilterDTO, filterDataPojo);
        String contentStr = JSON.toJSONString(filterDataPojo);
        JSONObject contentData = JsonHelperUtil.parseObject(contentStr);
        if (contentData == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.ORGANIZATION_STRUCTURE_TYPE_ERROR);
        }

        IndexFilterEntity filterEntity = indexFilterModel.getByCorpidAndUserId(corpid, userId);

        if (filterEntity == null) {
            filterEntity = new IndexFilterEntity();
            filterEntity.setCorpid(corpid);
            filterEntity.setUserId(userId);
        }
        filterEntity.setContentData(contentData);

        try {
            indexFilterModel.save(filterEntity);
        } catch (Exception e) {
            LOG.error("保存首页看板筛选偏好配置失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return saveFilterVO;
    }
    
    /**
     * 获取公司数据
     *
     * @param corpid   公司id
     * @param userId   员工id
     * @param platform 平台
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-02-28 23:16
     * @version v1.0
     * @since v1.0
     */
    private ChartCategoryInitVO getCompanyData(String corpid, String userId, String platform) throws XbbException {
        // 公司已启用的数据
        ChartCategoryInitDTO initDTO = new ChartCategoryInitDTO();
        initDTO.setCorpid(corpid);
        initDTO.setUserId(userId);
        initDTO.setPlatform(platform);

        Locale locale = LocaleContextHolder.getLocale();
        String lang = locale.toString();
        XbbResponse<ChartCategoryInitVO> initVOXbbResp = chartCategoryFeignClient.getIndexCategoryAndChart(initDTO, lang);

        if (!initVOXbbResp.isSuccess()) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, ErrorMessageConstant.FAILED_GET_BOARD_CONFIG_DATA);
        }
        return initVOXbbResp.getResult();
    }
    /**
     * 获取分类、图表
     * @param corpid   公司id
     * @param userId   员工id
     * @param platform 平台
     * @param leftSetDataList 左侧或移动端
     * @param rightSetDataList 右侧，移动端为null
     * @return com.xbongbong.pro.statistic.pojo.vo.ChartCategoryInitVO
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private ChartCategoryInitVO getCompanyData(String corpid, String userId, String platform, List<IndexSetDataPojo> leftSetDataList, List<IndexSetDataPojo> rightSetDataList) throws XbbException {
        ChartCategoryInitDTO initDTO = new ChartCategoryInitDTO();
        initDTO.setCorpid(corpid);
        initDTO.setUserId(userId);
        initDTO.setPlatform(platform);
        //防止不影响原left和right，new新的list处理
        List<IndexSetDataPojo> list = new ArrayList<>();
        if (Objects.nonNull(leftSetDataList)) {
            list.addAll(leftSetDataList);
        }
        if (Objects.nonNull(rightSetDataList)) {
            list.addAll(rightSetDataList);
        }
        for (IndexSetDataPojo pojo : list) {
            //外层chartCategoryType为图表的情况
            if (Objects.equals(pojo.getChartCategoryType(), ChartConstant.CHART_CATEGORY_TYPE_CHART)) {
                Integer statisticsType = pojo.getStatisticsType();
                Long chartCategoryId = pojo.getChartCategoryId();
                //最外层直接是图表的（发布到首页），则直接塞入对应系统、自定义图表id集合
                if (Objects.equals(statisticsType, StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                    //自定义指标
                    initDTO.getCustomChartIdSet().add(chartCategoryId);
                } else {
                    //else统一当做系统指标 - 因为IndexSetDataPojo内的系统指标可能没有statisticsType标识
                    initDTO.getSystemChartIdSet().add(chartCategoryId);
                }
            }
            //内层读取enableList、disableList内的（一定是图表，不会是分类）图表id
            packageChart(initDTO, pojo.getEnableList());
            packageChart(initDTO, pojo.getDisableList());
        }
        //通过feign调用统计服务，得到需要的分类、图表
        String lang = LocaleContextHolder.getLocale().toString();
        XbbResponse<ChartCategoryInitVO> initVOXbbResp = chartCategoryFeignClient.getIndexCategoryAndChart(initDTO, lang);
        if (!initVOXbbResp.isSuccess()) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, ErrorMessageConstant.FAILED_GET_BOARD_CONFIG_DATA);
        }
        return initVOXbbResp.getResult();
    }

    /**
     * 获取配置实体
     *
     * @param corpid    公司id
     * @param userId    用户id
     * @param platform  平台
     * @param boardType 首页分类
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-30 14:47
     * @version v1.0
     * @since v1.0
     */
    private IndexSetEntity getSetEntity(String corpid, String userId, String platform, Integer boardType) throws XbbException {
        IndexSetEntity setEntity = indexSetModel.getByBoardType(corpid, userId, boardType);
        if (setEntity == null) {
            // 获取公司配置
            List<IndexSetDataPojo> setDBList = systemChartHelp.getCompanyConfig(corpid, userId, platform, boardType);
            JSONArray contentData = new JSONArray();
            contentData.addAll(setDBList);
            // 初始化实体
            setEntity = new IndexSetEntity();
            setEntity.setCorpid(corpid);
            setEntity.setUserId(userId);
            setEntity.setBoardType(boardType);
            setEntity.setContentData(contentData);
        }
        return setEntity;
    }



    /**
     * 过虑配置：移除无用的配置
     *
     * @param companyList 公司配置
     * @param userList    个人配置
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-02 12:29
     * @version v1.0
     * @since v1.0
     */
    private List<IndexSetDataPojo> checkConfig4Save(List<IndexSetDataPojo> companyList, List<IndexSetDataPojo> userList,Boolean isCustom) {
        if (userList == null || userList.size() == 0) {
            return companyList;
        }

        // 公司级配置：头部和尾部的配置列表
        List<IndexSetDataPojo> headList = new ArrayList<>();
        List<IndexSetDataPojo> tailList = new ArrayList<>();
        // 添加只有公司配置(管理员分配的自定义首页不需要添加)
        if (null == isCustom || !isCustom){
            for (IndexSetDataPojo companyData : companyList) {
                long id = companyData.getChartCategoryId();
                int type = companyData.getChartCategoryType();
                boolean isAdd = true;
                boolean isHead = !Objects.equals(companyData.getSort(), BasicConstant.ZERO);
                for (IndexSetDataPojo userPojo : userList) {
                    long setId = userPojo.getChartCategoryId();
                    int setType = userPojo.getChartCategoryType();
                    if (id == setId && type == setType) {
                        isAdd = false;
                        break;
                    }
                }
                if (isAdd) {
                    if (isHead) {
                        headList.add(companyData);
                    } else {
                        tailList.add(companyData);
                    }
                }
            }
        }

        // 排序
        headList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        tailList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        userList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());

        List<IndexSetDataPojo> allList = new ArrayList<>();
        // 添加公司级头部配置
        allList.addAll(headList);
        // 添加个人配置
        allList.addAll(userList);
        // 添加公司级尾部配置
        allList.addAll(tailList);

        return allList;
    }

    /**
     * 过滤未启用的配置
     *
     * @param companyList 公司配置
     * @param userList    个人配置
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-01 09:02
     * @version v1.0
     * @since v1.0
     */
    private List<IndexSetDataPojo> checkConfig4Show(List<IndexSetDataPojo> companyList, List<IndexSetDataPojo> userList,String corpid,Integer right,Boolean isCustom) {

        if (userList == null || userList.size() == 0) {
            // 移除公司未启用列表
            companyList.removeIf(companyData -> !Objects.equals(companyData.getEnable(), BasicConstant.IS_USE));
            return companyList;
        }

        // 获取公司里的访客计划categoryId
        ChartCategoryEntity communicatePlanEntity = null;
        if (Objects.equals(right,BasicConstant.ONE)){
            HashMap<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("columns", "id");
            param.put("corpid", corpid);
            param.put("alias", ChartCategoryAliasEnum.COMMUNICATE_PLAN.getAlias());
            communicatePlanEntity = chartCategoryModel.getEntityByAlias(param);
        }

        // 个人已启用列表
        List<IndexSetDataPojo> enableList = new ArrayList<>();
        for (IndexSetDataPojo dataPojo : userList) {
            if (null != communicatePlanEntity && Objects.equals(dataPojo.getChartCategoryId(),communicatePlanEntity.getId()) && Objects.equals(dataPojo.getChartCategoryType(), ChartCategoryTypeEnum.WEB_INDEX_RIGHT.getCode())){
                dataPojo.setEnable(1);
                enableList.add(dataPojo);
                continue;
            }
            if (BasicConstant.IS_USE.equals(dataPojo.getEnable()) && !BasicConstant.ZERO.equals(dataPojo.getAppHide())) {
                enableList.add(dataPojo);
            }
        }

        // 个人已启用与公司已启用交集、非发布到首页的图表指标
        List<IndexSetDataPojo> newEnableList = new ArrayList<>();

        // 取交集(个人及公司已启用交集)
        for (IndexSetDataPojo dataPojo : enableList) {
            long id = dataPojo.getChartCategoryId();
            int type = dataPojo.getChartCategoryType();
            // 是否为自定义图表指标
            boolean isChart = type == ChartConstant.CHART_CATEGORY_TYPE_CHART;
            for (IndexSetDataPojo companyData : companyList) {
                if (id == companyData.getChartCategoryId() && type == companyData.getChartCategoryType()) {
                    newEnableList.add(dataPojo);
                    isChart = false;
                    break;
                }
            }
            // 非发布到首页的自定义图表指标
            if (isChart) {
                newEnableList.add(dataPojo);
            }
        }

        // 公司级配置：头部和尾部的配置列表
        List<IndexSetDataPojo> headList = new ArrayList<>();
        List<IndexSetDataPojo> tailList = new ArrayList<>();

        // 取差集(只公司已启用)
        if (!isCustom){
            for (IndexSetDataPojo companyData : companyList) {
                long id = companyData.getChartCategoryId();
                int type = companyData.getChartCategoryType();
                boolean isAdd = true;
                boolean isHead = !Objects.equals(companyData.getSort(), BasicConstant.ZERO);
                for (IndexSetDataPojo userPojo : userList) {
                    long setId = userPojo.getChartCategoryId();
                    int setType = userPojo.getChartCategoryType();
                    if (id == setId && type == setType) {
                        isAdd = false;
                        break;
                    }
                }
                if (isAdd) {
                    if (isHead) {
                        headList.add(companyData);
                    } else {
                        tailList.add(companyData);
                    }
                }
            }
        }


        // 排序
        headList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        tailList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        newEnableList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());

        List<IndexSetDataPojo> allList = new ArrayList<>();
        allList.addAll(headList);
        allList.addAll(newEnableList);
        allList.addAll(tailList);

        return allList;
    }


    // TODO 过虑权限
    /**
     *
     * @param loginUser
     * @param depIdIn
     * @param leftSetDataList 左侧或移动端
     * @param rightSetDataList 右侧，移动端为null
     * @param companyData  分类、图表信息
     * @return void
     * @throws
     * @author 宏晓
     * @since v1.0
     * @version v1.0
     * @update zcp
     */
    private void checkPermission(UserVO loginUser, Set<Long> depIdIn, List<IndexSetDataPojo> leftSetDataList, List<IndexSetDataPojo> rightSetDataList, ChartCategoryInitVO companyData) throws XbbException{
        // 超管权限不过虑权限
        if (loginUser.isAdminOrBoss()) {
            return;
        }
        // 左侧看板
        if (leftSetDataList != null && leftSetDataList.size() > 0) {
//            TODO 系统和自定义图表id一致时有问题
            //所有系统、和自定义图表map
            checkPermission(loginUser, depIdIn, leftSetDataList, companyData);
        }
        // 右侧看板
        if (rightSetDataList != null && rightSetDataList.size() > 0) {
            checkPermission(loginUser, depIdIn, rightSetDataList, companyData);
        }
    }

    private void checkPermission(UserVO loginUser, Set<Long> depIdIn, List<IndexSetDataPojo> setDataList,
                                 ChartCategoryInitVO companyData) throws XbbException{
        Map<Long, ChartCategoryEntity> categoryMap = companyData.getCategoryMap();
//        TODO 优先使用自定义的，因为Pro内改造前的chartList自定义图表后置入，封装map时如果id冲突后塞入的自定义图表会覆盖系统图表
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        List<ChartEntity> chartList = companyData.getChartList();
        // saas权限
        Set<String> saasPermissions = loginUser.getPermSet();
        // paas权限
        Map<Long, List<Long>> appMenuMap = chartPermissionHelp.getPaasPermissionMap(loginUser.getPaasPermissions());
        Iterator<IndexSetDataPojo> it = setDataList.iterator();
        while (it.hasNext()) {
            IndexSetDataPojo dataPojo = it.next();
            if (dataPojo.getChartCategoryType().equals(ChartConstant.CHART_CATEGORY_TYPE_CHART)) {
                ChartEntity chartEntity;
                if (Objects.equals(dataPojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                    chartEntity = customChartMap.get(dataPojo.getChartCategoryId());
                } else {
                    chartEntity = systemChartMap.get(dataPojo.getChartCategoryId());
                }
                if (chartEntity == null) {
                    it.remove();
                    continue;
                }
                // 权限过虑
                if (chartPermissionHelp.filterProPermission4Chart(loginUser,chartEntity, saasPermissions, appMenuMap)) {
                    it.remove();
                    continue;
                }
                // 图表中心权限
                if(!saasPermissions.contains(ProPermissionAliasEnum.CHART.getAlias())) {
                    it.remove();
                    continue;
                }
                // 指标权限
                if (chartPermissionHelp.filterPermission4SingleChart(loginUser, depIdIn, chartEntity)) {
                    it.remove();
                }
            } else {
                // alias
                ChartCategoryEntity categoryEntity = categoryMap.get(dataPojo.getChartCategoryId());
                if(categoryEntity == null) {
                    it.remove();
                    continue;
                }
                String alias = categoryEntity.getAlias();
                ChartCategoryAliasEnum aliasEnum = ChartCategoryAliasEnum.getByAlias(alias);
                if(aliasEnum == null) {
                    it.remove();
                    continue;
                }
                // 不用过虑权限的模板
                if (commonHelp.notFilterBoard(aliasEnum)) {
                    continue;
                }
                if (aliasEnum == ChartCategoryAliasEnum.REPORT_BOARD || aliasEnum == ChartCategoryAliasEnum.FUND_MANAGEMENT) {
                    // 过虑指标
                    checkPermission4Chart(loginUser, depIdIn, dataPojo, companyData);
                } else if(aliasEnum == ChartCategoryAliasEnum.PK) {

                    // 初始化pk榜范围配置
                    List<ChartEntity> pkChartList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    chartList.forEach(chartEntity -> {
                        if(Objects.equals(chartEntity.getChartType(), ChartTypeEnum.PK.getCode())
                                || Objects.equals(chartEntity.getChartType(), ChartTypeEnum.PK_CUSTOM.getCode())){
                            pkChartList.add(chartEntity);
                        }
                    });
                    chartPkRuleHelp.initPkSetRule(pkChartList, loginUser.getCorpid());

                    // 千人千面的pk榜过滤权限（谁可以看）
                    checkPKPermission4Chart(loginUser, dataPojo, companyData);
                } else if(aliasEnum == ChartCategoryAliasEnum.REMIND) {
                    // 是否包含：客户跟进记录、供应商跟进记录
                    if(!saasPermissions.contains(ProPermissionAliasEnum.CUSTOMER_COMMUNICATE.getAlias()) &&
                        !saasPermissions.contains(ProPermissionAliasEnum.SUPPLIER_COMMUNICATE.getAlias())) {
                        it.remove();
                    }
                } else if(aliasEnum == ChartCategoryAliasEnum.DATA_WARNING) {
                    // 数据中心
                    if(!(saasPermissions.contains(ProPermissionAliasEnum.DATA_CENTER.getAlias()) &&
                            Objects.equals(packageHelp.getFeeType(loginUser.getCorpid()),PackageTypeEnum.ULTIMATE.getType()))) {
                        it.remove();
                    }
                } else if (!saasPermissions.contains(aliasEnum.getProPermissionAlias())) {
                    it.remove();
                }
            }

        }
    }


    /**
     * 发布到首页的地图和漏斗图需要返回一些特定信息给前端
     * @param chartEntity
     * @param indexInitPojo
     */
    private void handleChart4Index(ChartEntity chartEntity, IndexInitPojo indexInitPojo){
        if (Objects.equals(chartEntity.getChartType(),ChartTypeEnum.MAP_CUSTOM.getCode())){
            JSONObject explains = chartEntity.getExplains();
            if(explains != null ){
                indexInitPojo.setMapDistrict(explains.getString(StringConstant.MAP_DISTRICT));
                indexInitPojo.setMap(JSON.parseObject(JSON.toJSONString(explains.get(StringConstant.MAP))));
            }
        }
        if (Objects.equals(chartEntity.getChartType(),ChartTypeEnum.FUNNEL.getCode())){
            JSONObject explains = chartEntity.getExplains();
            if(explains != null ){
                indexInitPojo.setFunnel(JSON.parseObject(JSON.toJSONString(explains.get(StringConstant.FUNNEL))));
            }
        }
    }

    // TODO 过虑权限
    private void checkPermission4Chart(UserVO loginUser, Set<Long> depIdIn, IndexSetDataPojo setDataPojo, ChartCategoryInitVO companyData) {
        // 超管权限不过虑权限
        if (loginUser.isAdminOrBoss()) {
            return;
        }
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        // saas权限
        Set<String> saasPermissions = loginUser.getPermSet();
        // paas权限
        Map<Long, List<Long>> appMenuMap = chartPermissionHelp.getPaasPermissionMap(loginUser.getPaasPermissions());
        List<IndexBoardChartSavePojo> enableList = setDataPojo.getEnableList();
        List<IndexBoardChartSavePojo> disableList = setDataPojo.getDisableList();
        if (enableList != null) {
            Iterator<IndexBoardChartSavePojo> it = enableList.iterator();
            while (it.hasNext()) {
                IndexBoardChartSavePojo pojo = it.next();
                ChartEntity chartEntity;
                if (Objects.equals(pojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                    chartEntity = customChartMap.get(pojo.getId());
                } else {
                    chartEntity = systemChartMap.get(pojo.getId());
                }
                if(chartEntity == null) {
                    continue;
                }
                // 权限过虑
                if (chartPermissionHelp.filterProPermission4Chart(loginUser,chartEntity, saasPermissions, appMenuMap)) {
                    it.remove();
                }
            }
        }
        if (disableList != null) {
            Iterator<IndexBoardChartSavePojo> it = disableList.iterator();
            while (it.hasNext()) {
                IndexBoardChartSavePojo pojo = it.next();
                ChartEntity chartEntity;
                if (Objects.equals(pojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                    chartEntity = customChartMap.get(pojo.getId());
                } else {
                    chartEntity = systemChartMap.get(pojo.getId());
                }
                if(chartEntity == null) {
                    continue;
                }
                // 权限过虑
                if (chartPermissionHelp.filterProPermission4Chart(loginUser,chartEntity, saasPermissions, appMenuMap)) {
                    it.remove();
                }
            }
        }

    }

    // TODO 过虑权限
    private void checkPKPermission4Chart(UserVO loginUser, IndexSetDataPojo setDataPojo, ChartCategoryInitVO companyData) throws XbbException{
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        String userId = loginUser.getUserId();
        List<String> userIdIn = new ArrayList<>(Arrays.asList(userId));
        String corpid = loginUser.getCorpid();

        List<IndexBoardChartSavePojo> enableList = setDataPojo.getEnableList();
        if (enableList != null) {
            Iterator<IndexBoardChartSavePojo> it = enableList.iterator();
            while (it.hasNext()) {
                IndexBoardChartSavePojo pojo = it.next();
                ChartEntity chartEntity;
                if (Objects.equals(pojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                    chartEntity = customChartMap.get(pojo.getId());
                } else {
                    chartEntity = systemChartMap.get(pojo.getId());
                }
                if(chartEntity == null) {
                    continue;
                }
                JSONArray scopeRule = chartEntity.getScopeRule();
                if(scopeRule == null) {
                    continue;
                }
                List<String> scopeRuleIdList = chartPkRuleHelp.calculationUserList(userIdIn, corpid, scopeRule);
                if(!scopeRuleIdList.contains(userId)){
                    it.remove();
                }
            }
        }
    }

    private void checkPermission4ConfigChart(UserVO loginUser, Set<Long> depIdIn, List<IndexBoardChartPojo> enableList, List<IndexBoardChartPojo> disableList, Map<Long, ChartEntity> systemChartMap, Map<Long, ChartEntity> customChartMap) throws XbbException {
        // 超管权限不过虑权限
        if (loginUser.isAdminOrBoss()) {
            return;
        }
        // saas权限
        Set<String> saasPermissions = loginUser.getPermSet();
        // paas权限
        Map<Long, List<Long>> appMenuMap = chartPermissionHelp.getPaasPermissionMap(loginUser.getPaasPermissions());

        UserEntity userEntity = BeanUtil.copyProperties(loginUser, UserEntity.class, false);

        if (enableList != null) {
            Iterator<IndexBoardChartPojo> it = enableList.iterator();
            while (it.hasNext()) {
                IndexBoardChartPojo pojo = it.next();
                ChartEntity chartEntity;
                if (Objects.equals(pojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                    chartEntity = customChartMap.get(pojo.getId());
                } else {
                    chartEntity = systemChartMap.get(pojo.getId());
                }
                if(chartEntity == null) {
                    continue;
                }
                // 权限过虑
                if (chartPermissionHelp.filterProPermission4Chart(loginUser,chartEntity, saasPermissions, appMenuMap)) {
                    it.remove();
                }
                // pk把不在可见范围内的过滤掉
                if((Objects.equals(ChartTypeEnum.PK.getCode(),chartEntity.getChartType()) || Objects.equals(ChartTypeEnum.PK_CUSTOM.getCode(),chartEntity.getChartType()))
                        && !pkRuleHelp.checkLoginUserCanSee(chartEntity, userEntity)) {
                    it.remove();
                }
            }
        }
        if (disableList != null) {
            Iterator<IndexBoardChartPojo> it = disableList.iterator();
            while (it.hasNext()) {
                IndexBoardChartPojo pojo = it.next();
                ChartEntity chartEntity;
                if (Objects.equals(pojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                    chartEntity = customChartMap.get(pojo.getId());
                } else {
                    chartEntity = systemChartMap.get(pojo.getId());
                }
                if(chartEntity == null) {
                    continue;
                }
                // 权限过虑
                if (chartPermissionHelp.filterProPermission4Chart(loginUser,chartEntity, saasPermissions, appMenuMap)) {
                    it.remove();
                }
                // pk把不在可见范围内的过滤掉
                if((Objects.equals(ChartTypeEnum.PK.getCode(),chartEntity.getChartType()) || Objects.equals(ChartTypeEnum.PK_CUSTOM.getCode(),chartEntity.getChartType()))
                        && !pkRuleHelp.checkLoginUserCanSee(chartEntity, userEntity)) {
                    it.remove();
                }
            }
        }
    }

    /**
     * 封装（web-初始化）展示数据
     *
     * @param loginUser
     * @param setList      设置列表
     * @param companyData  分类、图表信息
     * @param count        是否是初始化公司
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-18 09:51
     * @version v1.0
     * @since v1.0
     */
    private List<IndexInitPojo> formatInitWeb(UserVO loginUser, List<IndexSetDataPojo> setList, ChartCategoryInitVO companyData, Integer count, Integer right,Boolean isCustom) throws XbbException {
        return formatInitData(loginUser, setList, companyData, StringConstant.PLATFORM_WEB, count, right,isCustom);
    }

    /**
     * 封装（app-初始化）展示数据
     *
     * @param setList      设置列表
     * @param companyData  分类、图表信息
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-18 14:14
     * @version v1.0
     * @since v1.0
     */
    private List<IndexInitPojo> formatInitApp(UserVO loginUser, List<IndexSetDataPojo> setList, ChartCategoryInitVO companyData, Integer right,Boolean isCustom) throws XbbException {
        return formatInitData(loginUser, setList, companyData, StringConstant.PLATFORM_DINGTALK, BasicConstant.ZERO, right,isCustom);
    }

    /**
     * 封装（初始化）展示数据
     *
     * @param setList      设置列表
     * @param companyData  分类、图表信息
     * @param platform     平台
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-18 14:15
     * @version v1.0
     * @since v1.0
     */
    private List<IndexInitPojo> formatInitData(UserVO loginUser, List<IndexSetDataPojo> setList, ChartCategoryInitVO companyData,
                                               String platform, Integer count, Integer right,Boolean isCustom) throws XbbException{
        String corpid = loginUser.getCorpid();
        Map<Long, ChartCategoryEntity> categoryMap = companyData.getCategoryMap();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();

        List<IndexInitPojo> list = new ArrayList<>();

        // web端右侧看板跳转到列表需要使用到menuId,appId
        List<String> aliasList = Arrays.asList(XbbRefTypeEnum.COMMUNICATE_PLAN.getAlias(),
                XbbRefTypeEnum.STOCK_SEARCH.getAlias(), XbbRefTypeEnum.WORK_ORDER.getAlias() ,XbbRefTypeEnum.WORK_ORDER_V2.getAlias() ,XbbRefTypeEnum.CLUE.getAlias());
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("aliasIn", aliasList);
        param.put("enable", BasicConstant.IS_USE);
        List<PaasMenuEntity> formEntityList = paasMenuModel.findEntitys(param);
        Map<Integer, AppMenuFormIdPojo> formEntityExtMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.clear();
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        formEntityList.forEach(item -> {
            AppMenuFormIdPojo pojo = new AppMenuFormIdPojo();
            XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByAlias(item.getAlias());
            pojo.setMenuId(item.getId());
            pojo.setAppId(item.getAppId());
            formEntityExtMap.put(refTypeEnum.getCode(), pojo);
        });
        // 多模板业务表单
        List<PaasFormEntityExt> paasFormEntityList = paasFormModel.getEnableFormList(loginUser.getCorpid(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
        List<PaasFormEntityExt> customerForm = paasFormModel.getEnableFormListDistributor(loginUser.getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), 0);
        List<PaasFormEntityExt> enableFormList = paasFormModel.getEnableFormList(loginUser.getCorpid(), XbbRefTypeEnum.CLUE.getCode());
        List<PaasFormEntityExt> workOrderV2paasFormEntityList = paasFormModel.getEnableFormList(loginUser.getCorpid(), XbbRefTypeEnum.WORK_ORDER_V2.getCode());
        paasFormEntityList.addAll(customerForm);
        paasFormEntityList.addAll(enableFormList);
        paasFormEntityList.addAll(workOrderV2paasFormEntityList);
        //权限校验
        paasFormService.removeByPermission(paasFormEntityList, loginUser);
        // 获取套餐下的功能
        List<String> featureList = packageHelp.getFeatureList(corpid);
        // 获取套餐使用量
        Integer useNum = updatePackageRedisService.getTotalPackageLimit(corpid, ValueAddedTypeEnum.CUSTOM_CHART_NUM);
        Integer num = updatePackageRedisService.getUnusedNumPackageLimit(corpid, ValueAddedTypeEnum.CUSTOM_CHART_NUM);

        List<Long> chartIdList = updatePackageRedisService.getPackageTotalChartId(corpid);
        boolean isAdmin = loginUser.isAdmin();
        // 是否是有首页管理权限
        boolean homePageManagePermission = loginUser.getPermSet().contains(ProPermissionAliasEnum.HOME_PAGE_MANAGE.getAlias());
        Map<Integer, List<AppMenuFormIdPojo>> mutilTemplateFormMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<AppMenuFormIdPojo> appMenuFormIdPojoList;
        AppMenuFormIdPojo appMenuFormIdPojo;
        for (PaasFormEntityExt item : paasFormEntityList) {
            appMenuFormIdPojoList = mutilTemplateFormMap.getOrDefault(item.getBusinessType(), new ArrayList<>());
            appMenuFormIdPojo  = new AppMenuFormIdPojo();
            appMenuFormIdPojo.setAppId(item.getAppId());
            appMenuFormIdPojo.setMenuId(item.getMenuId());
            appMenuFormIdPojo.setFormId(item.getId());
            appMenuFormIdPojo.setFormName(item.getName());
            appMenuFormIdPojo.setBusinessType(item.getBusinessType());
            appMenuFormIdPojoList.add(appMenuFormIdPojo);
            mutilTemplateFormMap.put(item.getBusinessType(), appMenuFormIdPojoList);
        }
        int communicateIndex = 0;
        IndexInitPojo communicatePlanPojo = null;
        for (IndexSetDataPojo pojo : setList) {
            int chartCategoryType = pojo.getChartCategoryType();
            Integer statisticsType = pojo.getStatisticsType();
            // 默认系统看板
            if (chartCategoryType == ChartConstant.CHART_CATEGORY_TYPE_CATEGORY && categoryMap.containsKey(pojo.getChartCategoryId())) {
//                IndexInitPojo initPojo = formatDefaultInitData(categoryMap.get(pojo.getChartCategoryId()), pojo, enableSystemIds, enableCustomIds, chartList, platform, formEntityExtMap, mutilTemplateFormMap);
                IndexInitPojo initPojo = formatDefaultInitData(corpid, pojo, companyData, platform, formEntityExtMap, mutilTemplateFormMap);
                if (Objects.isNull(initPojo)){
                    continue;
                }
                // 过虑库预警
                if (Objects.equals(ChartCategoryAliasEnum.STOCK_WARNING.getAlias(), initPojo.getAlias())) {
                    continue;
                }
                // 访客计划设置置灰,以及有的话就开启
                if (Objects.equals(ChartCategoryAliasEnum.COMMUNICATE_PLAN.getAlias(), initPojo.getAlias())) {
                    initPojo.setForbidden(PaasConstant.ENABLE_FORBIDDEN);
                    initPojo.setEnable(1);
                    communicatePlanPojo = initPojo;
                    communicateIndex = list.size();
                }
                if (Objects.nonNull(isCustom) && isCustom && !isAdmin && !homePageManagePermission){
                    initPojo.setSetFlag(false);
                }
                list.add(initPojo);
            } else if (chartCategoryType == ChartConstant.CHART_CATEGORY_TYPE_CHART) {
                IndexInitPojo initPojo = null;
                if (Objects.equals(statisticsType, StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                    if (customChartMap.containsKey(pojo.getChartCategoryId())) {
                        // 图表中心发布到首页
                        initPojo = formatCustomInitData(customChartMap.get(pojo.getChartCategoryId()), pojo.getEnable(), pojo.getSecondCategoryId(), mutilTemplateFormMap,pojo.getAppHide());
                        boolean packageLimitFlag = packageHelp.packageLimitFlag(chartIdList, pojo.getChartCategoryId(), statisticsType, num, featureList);
                        if (Objects.nonNull(initPojo) && packageLimitFlag) {
                            initPojo.setPackageLimit(1);
                            initPojo.setPackageLimitMsg(String.format(I18nMessageUtil.getMessage(PackageConstant.CUSTOM_CHART_PACKAGE_LIMIT_MESSAGE), useNum));
                            if(isAdmin) {
                                initPojo.setUpgrade(1);
                            }
                        }
                    }
                } else {
                    if (systemChartMap.containsKey(pojo.getChartCategoryId())) {
                        // 图表中心发布到首页
                        initPojo = formatCustomInitData(systemChartMap.get(pojo.getChartCategoryId()), pojo.getEnable(), pojo.getSecondCategoryId(), mutilTemplateFormMap,pojo.getAppHide());
                    }
                }
                if (initPojo != null) {
                    ChartEntity chartEntity;
                    if (Objects.equals(initPojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                        chartEntity = customChartMap.get(initPojo.getChartCategoryId());
                    } else {
                        chartEntity = systemChartMap.get(initPojo.getChartCategoryId());
                    }
                    // 地图和漏斗图首页调用特殊处理
                    handleChart4Index(chartEntity, initPojo);
                    if (Objects.nonNull(isCustom) && isCustom && !isAdmin && !homePageManagePermission){
                        initPojo.setSetFlag(false);
                    }
                    list.add(initPojo);
                }
            }
        }
        // 访客计划设置置顶
        if (null != communicatePlanPojo){
            list.remove(communicateIndex);
            list.add(0,communicatePlanPojo);
        }
        // 初始化web端右侧客服看板默认最后放置
        if(Objects.equals(right, BasicConstant.ONE) && StringConstant.PLATFORM_WEB.equals(platform)){
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid", corpid);
            params.put("negUserId", "0");
            params.put("del", DelEnum.NORMAL.getDel());
            Integer negCount = indexSetModel.getEntitysCount(params);
            if(Objects.equals(count, BasicConstant.ZERO) || Objects.equals(negCount, BasicConstant.ZERO)){
                Iterator<IndexInitPojo> iterator = list.iterator();
                while (iterator.hasNext()){
                    IndexInitPojo initPojo = iterator.next();
                    if(Objects.equals(initPojo.getAlias(), ChartCategoryAliasEnum.KE_FU.getAlias())){
                        iterator.remove();
                        break;
                    }
                }
            }
        }

        return list;
    }

//    /**
//     * 格式化默认系统看板数据
//     *
//     * @param categoryMap 分类map
//     * @param pojo        首页看板数据pojo
//     * @param enableIds   已启用id列表
//     * @param chartList   指标列表
//     * @param platform    平台
//     * @return
//     * @throws
//     * @author hongxiao
//     * @date: 2019-03-28 17:22
//     * @version v1.0
//     * @since v1.0
//     */
//    private IndexInitPojo formatDetaultInitData(Map<Long, ChartCategoryEntity> categoryMap, IndexSetDataPojo pojo,
//                                                List<Long> enableIds, List<ChartEntity> chartList, String platform, Map<Integer, AppMenuFormIdPojo> formEntityExtMap, Map<Integer, List<AppMenuFormIdPojo>> mutilTemplateFormMap) throws XbbException {
//        // 套餐
//        boolean standardWithFeeType = marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(chartList.get(0).getCorpid());
//        Integer feeType = packageHelp.getFeeType(chartList.get(0).getCorpid());
//        List<String> strings = Arrays.asList("saleClue", "marketActivityAnalysis", "clueAnalysis", "pkUserLeadConverAnalysis");
//        ChartCategoryEntity entity = categoryMap.get(pojo.getChartCategoryId());
//        String alias = entity.getAlias();
//        if (standardWithFeeType && strings.contains(alias)){
//            return null;
//        }
//        if (!Objects.equals(feeType,PackageTypeEnum.ULTIMATE.getType()) && Objects.equals(alias,ChartCategoryAliasEnum.DATA_WARNING.getAlias())){
//            return null;
//        }
//        IndexInitPojo initPojo = new IndexInitPojo();
//        initPojo.setName(entity.getName());
//        if (Objects.equals(LocaleContextHolder.getLocale().getLanguage(), I18nStringConstant.ENGLISH_LANGUAGE)) {
//            // 切成英文的字段展示
//            initPojo.setName(entity.getNameEn());
//        }
//        initPojo.setAlias(alias);
//        initPojo.setChartCategoryId(entity.getId());
//        initPojo.setChartCategoryType(ChartConstant.CHART_CATEGORY_TYPE_CATEGORY);
//        initPojo.setIdIn(enableIds);
//        initPojo.setShowType(pojo.getShowType());
//        initPojo.setEnable(pojo.getEnable());
//        initPojo.setStatisticsType(StatisticsTypeEnum.SYSTEM_STATISTIC.getCode());
//
//        // 销售简报
//        boolean isReportFlag = isReportBoard(alias);
//        // 客户分析，合同分析，回款分析，付款分析，采购分析，工单分析
//        boolean isChartDataFlag = isSystemChartBoard(alias);
//        // 机会
//        boolean isOpportunityFlag = isOpportunityBoard(alias);
//        // pk榜，业绩目标完成情况
//        boolean isPerformanceFlag = isPerformanceBoard(alias);
//        boolean isPkFlag = isPkBoard(alias);
//        /*
//         * web:公告，销售简报，待处理审批，审批进展，待处理工单，访客计划，跟进提醒，库存预警，客服
//         * app:销售简报，待处理审批，审批进展，待处理工单，访客计划，跟进提醒，库存预警
//         */
//        boolean isRightFlag = isRightBoard(alias, platform);
//        boolean isForgetOrCareFlag = isForgetOrCareBoard(alias);
//        boolean isFundFlag = isFundBoard(alias);
//        boolean isClueFlag = isClue(alias);
//
//        // 是否有指标设置：简报看板，业绩目标，pk榜，客户/机会/合同/回款/付款/采购/工单/销售线索
//        boolean setFlag = isReportFlag || isChartDataFlag || isOpportunityFlag || isPerformanceFlag || isPkFlag || isFundFlag || isClueFlag;
//        initPojo.setSetFlag(setFlag);
//
//        if (isReportFlag || isForgetOrCareFlag) {
//            JSONArray childList = formatReportBoard(pojo, chartList, enableIds);
//            initPojo.setChildList(childList);
//            // 重设指标idIn
//            initPojo.setIdIn(enableIds);
//        } else if (isChartDataFlag) {
//            JSONArray childList = formatSystemChartData(pojo, chartList, platform);
//            initPojo.setChildList(childList);
//            initPojo.setSetFlag(true);
//        } else if (isOpportunityFlag) {
//            List<AppMenuFormIdPojo> appMenuFormIdPojoList = mutilTemplateFormMap.get(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
//            Long formId = null;
//            if (CollectionsUtil.isNotEmpty(appMenuFormIdPojoList)) {
//                AppMenuFormIdPojo appMenuFormIdPojo = appMenuFormIdPojoList.get(0);
//                formId = appMenuFormIdPojo.getFormId();
//                initPojo.setAppMenuFormIdPojoList(appMenuFormIdPojoList);
//            }
//            JSONArray childList = formatOpportinutyData(pojo, chartList, platform, formId);
//            initPojo.setChildList(childList);
//            initPojo.setSetFlag(true);
//        } else if (isPerformanceFlag) {
//            // 业绩完成情况
//            JSONArray childList = formatPerformanceData(pojo, chartList, enableIds);
//            initPojo.setChildList(childList);
//            initPojo.setSetFlag(true);
//            initPojo.setIdIn(enableIds);
//        } else if (isPkFlag) {
//            JSONArray childList = formatPkData(pojo, chartList, enableIds);
//            initPojo.setChildList(childList);
//            initPojo.setSetFlag(true);
//            initPojo.setIdIn(enableIds);
//        } else if (isFundFlag) {
//            JSONArray childList = formatFundManagement(pojo, chartList, enableIds);
//            initPojo.setChildList(childList);
//        } else if (isRightFlag) {
//            initPojo.setIdIn(null);
//            initPojo.setShowType(null);
//
//            // 跳转列表页需要用到的参数
//            ChartCategoryAliasEnum jump2BusinessEnum = ChartCategoryAliasEnum.jump2BusinessByAlias(alias);
//            if (jump2BusinessEnum != null) {
//                AppMenuFormIdPojo appMenuFormIdPojo = formEntityExtMap.get(jump2BusinessEnum.getBusinessType());
//                JSONObject subBusinessObj = new JSONObject();
//                subBusinessObj.put("saasMark", SaasMarkEnum.SAAS.getCode());
//                subBusinessObj.put("subBusinessType", jump2BusinessEnum.getBusinessType());
//                if (appMenuFormIdPojo != null) {
//                    subBusinessObj.put("appId", appMenuFormIdPojo.getAppId());
//                    subBusinessObj.put("menuId", appMenuFormIdPojo.getMenuId());
//                }
//                initPojo.setSubBusiness(subBusinessObj);
//            }
//        }
//        return initPojo;
//    }

    private IndexInitPojo formatDefaultInitData(String corpid, IndexSetDataPojo pojo, ChartCategoryInitVO companyData, String platform, Map<Integer, AppMenuFormIdPojo> formEntityExtMap, Map<Integer, List<AppMenuFormIdPojo>> mutilTemplateFormMap) throws XbbException {
        // 套餐
        Map<Long, ChartCategoryEntity> categoryMap = companyData.getCategoryMap();
        boolean standardWithFeeType = marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(corpid);
        Integer feeType = packageHelp.getFeeType(corpid);
        List<String> strings = Arrays.asList("saleClue", "marketActivityAnalysis", "clueAnalysis", "pkUserLeadConverAnalysis");
        ChartCategoryEntity entity = categoryMap.get(pojo.getChartCategoryId());
        String alias = entity.getAlias();
        if (standardWithFeeType && strings.contains(alias)){
            return null;
        }
        if (!Objects.equals(feeType,PackageTypeEnum.ULTIMATE.getType()) && Objects.equals(alias,ChartCategoryAliasEnum.DATA_WARNING.getAlias())){
            return null;
        }

        // 区分系统和自定义指标
        List<Long> enableSystemIds = new ArrayList<>();
        List<Long> enableCustomIds = new ArrayList<>();
        List<ChartIdPojo> chartIdPojoList = new ArrayList<>();
        for (IndexBoardChartSavePojo savePojo : pojo.getEnableList()) {
            ChartIdPojo chartIdPojo = new ChartIdPojo();
            chartIdPojo.setId(savePojo.getId());
            chartIdPojo.setStatisticsType(savePojo.getStatisticsType());
            chartIdPojoList.add(chartIdPojo);
            if (Objects.equals(savePojo.getStatisticsType() , StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                enableCustomIds.add(savePojo.getId());
            } else {
                enableSystemIds.add(savePojo.getId());
            }
        }

        IndexInitPojo initPojo = new IndexInitPojo();
        initPojo.setName(entity.getName());
        if (Objects.equals(LocaleContextHolder.getLocale().getLanguage(), I18nStringConstant.ENGLISH_LANGUAGE)) {
            // 切成英文的字段展示
            initPojo.setName(entity.getNameEn());
        }
        initPojo.setAlias(alias);
        initPojo.setChartCategoryId(entity.getId());
        initPojo.setChartCategoryType(ChartConstant.CHART_CATEGORY_TYPE_CATEGORY);
        initPojo.setIdIn(enableSystemIds);
        initPojo.setChartIdIn(chartIdPojoList);
        initPojo.setShowType(pojo.getShowType());
        initPojo.setEnable(pojo.getEnable());
        initPojo.setStatisticsType(StatisticsTypeEnum.SYSTEM_STATISTIC.getCode());
        initPojo.setAppHide(pojo.getAppHide());

        // 销售简报
        boolean isReportFlag = isReportBoard(alias);
        // 客户分析，合同分析，回款分析，付款分析，采购分析，工单分析
        boolean isChartDataFlag = isSystemChartBoard(alias);
        // 机会
        boolean isOpportunityFlag = isOpportunityBoard(alias);
        // pk榜，业绩目标完成情况
        boolean isPerformanceFlag = isPerformanceBoard(alias);
        boolean isPkFlag = isPkBoard(alias);
        /*
         * web:公告，销售简报，待处理审批，审批进展，待处理工单，访客计划，跟进提醒，库存预警，客服
         * app:销售简报，待处理审批，审批进展，待处理工单，访客计划，跟进提醒，库存预警
         */
        boolean isRightFlag = isRightBoard(alias, platform);
        boolean isForgetOrCareFlag = isForgetOrCareBoard(alias);
        boolean isFundFlag = isFundBoard(alias);
        boolean isClueFlag = isClue(alias);

        // 是否有指标设置：简报看板，业绩目标，pk榜，客户/机会/合同/回款/付款/采购/工单/销售线索
        boolean setFlag = isReportFlag || isChartDataFlag || isOpportunityFlag || isPerformanceFlag || isPkFlag || isFundFlag || isClueFlag;
        initPojo.setSetFlag(setFlag);

        if (isReportFlag || isForgetOrCareFlag) {
            JSONArray childList = formatReportBoard(pojo, companyData, enableSystemIds, chartIdPojoList);
            initPojo.setChildList(childList);
            // 重设指标idIn
            initPojo.setIdIn(enableSystemIds);
            initPojo.setChartIdIn(chartIdPojoList);
        } else if (isChartDataFlag) {
            JSONArray childList = formatSystemChartData(pojo, companyData, platform);
            initPojo.setChildList(childList);
            initPojo.setSetFlag(true);
        } else if (isOpportunityFlag) {
            List<AppMenuFormIdPojo> appMenuFormIdPojoList = mutilTemplateFormMap.get(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
            Long formId = null;
            if (CollectionsUtil.isNotEmpty(appMenuFormIdPojoList)) {
                AppMenuFormIdPojo appMenuFormIdPojo = appMenuFormIdPojoList.get(0);
                formId = appMenuFormIdPojo.getFormId();
                initPojo.setAppMenuFormIdPojoList(appMenuFormIdPojoList);
            }
            JSONArray childList = formatOpportunityData(pojo, companyData, platform, formId);
            initPojo.setChildList(childList);
            initPojo.setSetFlag(true);
        } else if (isPerformanceFlag) {
            // 业绩完成情况
            JSONArray childList = formatPerformanceData(pojo, companyData, enableSystemIds, chartIdPojoList);
            initPojo.setChildList(childList);
            initPojo.setSetFlag(true);
            initPojo.setIdIn(enableSystemIds);
            initPojo.setChartIdIn(chartIdPojoList);
        } else if (isPkFlag) {
            JSONArray childList = formatPkData(pojo, companyData, enableSystemIds, chartIdPojoList);
            initPojo.setChildList(childList);
            initPojo.setSetFlag(true);
            initPojo.setIdIn(enableSystemIds);
            initPojo.setChartIdIn(chartIdPojoList);
        } else if (isFundFlag) {
            JSONArray childList = formatFundManagement(pojo, companyData, enableSystemIds, chartIdPojoList);
            initPojo.setChildList(childList);
        } else if (isRightFlag) {
            initPojo.setIdIn(null);
            initPojo.setShowType(null);

            // 跳转列表页需要用到的参数
            ChartCategoryAliasEnum jump2BusinessEnum = ChartCategoryAliasEnum.jump2BusinessByAlias(alias);
            if (jump2BusinessEnum != null) {
                AppMenuFormIdPojo appMenuFormIdPojo = formEntityExtMap.get(jump2BusinessEnum.getBusinessType());
                JSONObject subBusinessObj = new JSONObject();
                subBusinessObj.put("saasMark", SaasMarkEnum.SAAS.getCode());
                subBusinessObj.put("subBusinessType", jump2BusinessEnum.getBusinessType());
                if (appMenuFormIdPojo != null) {
                    subBusinessObj.put("appId", appMenuFormIdPojo.getAppId());
                    subBusinessObj.put("menuId", appMenuFormIdPojo.getMenuId());
                }
                initPojo.setSubBusiness(subBusinessObj);
            }
        }
//        // 左侧看板没有chartIdIn不展示
//        boolean needShowAlias = Objects.equals(alias, ChartCategoryAliasEnum.RAIDERS.getAlias()) || isPkFlag || isPerformanceFlag;
//        if (!isRightFlag && !needShowAlias && CollectionsUtil.isEmpty(initPojo.getChartIdIn())) {
//            return null;
//        }
        // 设置数值格式设置按钮显隐
        if (NumFormatEnum.isNeedAmount4Index(alias)) {
            initPojo.setIsAmount(1);
        }
        return initPojo;
    }

    private boolean isClue(String alias) {
        return  ChartCategoryAliasEnum.SALE_CLUE_CHART.getAlias().equals(alias);
    }

    /**
     * 获取图表中心发送到首页
     *
     * @param entity           指标实体
     * @param enable           是否启用
     * @param secondCategoryId 二级分类id(跳转到图表中心，定位使用)
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-28 17:24
     * @version v1.0
     * @since v1.0
     */
    private IndexInitPojo formatCustomInitData(ChartEntity entity, Integer enable, Long secondCategoryId, Map<Integer, List<AppMenuFormIdPojo>> mutilTemplateFormMap,Integer appHide) throws XbbException {
        // 展示方式
        Integer chartType = entity.getChartType();
        // 指标类型
        Integer statisticsType = entity.getStatisticsType();
        List<Long> idIn = Collections.singletonList(entity.getId());
        List<ChartIdPojo> chartIdIn = new ArrayList<>();
        ChartIdPojo chartIdPojo = new ChartIdPojo();
        chartIdPojo.setId(entity.getId());
        chartIdPojo.setStatisticsType(entity.getStatisticsType());
        if(Objects.equals(StatisticsTypeEnum.CUSTOM_STATISTIC.getCode(),entity.getStatisticsType())){
            chartIdPojo.setSingle(entity.getSingle());
        }
        chartIdIn.add(chartIdPojo);

        boolean standardWithFeeType = marketManagementBusinessHelp.isStandardWithFeeType(entity.getCorpid());
        List<String> standardSystemCode = SystemCodeEnum.getStandardSystemCode();
        String systemCode = entity.getSystemCode();
        if (standardWithFeeType && standardSystemCode.contains(systemCode)){
            return null;
        }

        IndexInitPojo initPojo = new IndexInitPojo();
        initPojo.setName(entity.getName());
        if (Objects.equals(LocaleContextHolder.getLocale().getLanguage(), I18nStringConstant.ENGLISH_LANGUAGE)) {
            // 切成英文的字段展示
            initPojo.setName(entity.getNameEn());
        }

        //通过Alias改变前端路由(只给工单2.0加,给其他图加前端首页展示不了图)
        ChartCategoryEntity chartCategoryEntity = chartCategoryModel.getByKey(secondCategoryId, entity.getCorpid());
        if (Objects.nonNull(chartCategoryEntity) && Objects.nonNull(chartCategoryEntity.getAlias()) && (chartCategoryEntity.getAlias().contains("workOrderV2") || chartCategoryEntity.getAlias().contains("receipt"))){
            initPojo.setAlias(chartCategoryEntity.getAlias());
        }

        initPojo.setChartCategoryId(entity.getId());
        initPojo.setChartCategoryType(ChartConstant.CHART_CATEGORY_TYPE_CHART);
        initPojo.setIdIn(idIn);
        initPojo.setChartIdIn(chartIdIn);
        initPojo.setShowType(entity.getChartType());
        initPojo.setStatisticsType(statisticsType);
        initPojo.setEnable(enable);
        initPojo.setAppHide(appHide);
        // 二级分类id(跳转到图表中心，定位使用)
        if (secondCategoryId != null) {
            initPojo.setSecondCategoryId(secondCategoryId);
        }

        // 未知类型不处理
        StatisticsTypeEnum statisticsTypeEnum = StatisticsTypeEnum.getByCode(statisticsType);
        if (statisticsTypeEnum == StatisticsTypeEnum.UNKNOWN) {
            return null;
        }
        // 发送到首页的图表(拆线图、柱状图、饼图、雷达图、面积图、漏斗图-saas特有、地图-saas特有)
        ChartResultDetailVO chartResultVO = new ChartResultDetailVO();
        chartResultVO.setChartId(entity.getId());
        // 未知展示方式不处理
        ChartTypeEnum typeEnum = ChartTypeEnum.getByCode(chartType);
        if (typeEnum == null) {
            return null;
        }
        switch (typeEnum) {
            // 折线图、柱状图
            case BAR_CHART:
            case LINE_CHART:
                // 系统指标
                if (statisticsTypeEnum == StatisticsTypeEnum.SYSTEM_STATISTIC) {
                    // 只添加图，平台设置为dingtalk
                    setLineChartData(entity, chartResultVO, StringConstant.PLATFORM_DINGTALK);
                    if (Objects.equals(entity.getSystemCode(), SystemCodeEnum.CLUE_SOURCE.getSystemCode()) || Objects.equals(entity.getSystemCode(), SystemCodeEnum.CLUE_INVALID_RESOURCE.getSystemCode())) {
                        List<AppMenuFormIdPojo> appMenuFormIdPojos = (List<AppMenuFormIdPojo>) CloneUtil.deepClone(mutilTemplateFormMap.get(XbbRefTypeEnum.CLUE.getCode()));
                        if (CollectionsUtil.isNotEmpty(appMenuFormIdPojos)) {
                            appMenuFormIdPojos.forEach(item -> item.setSourceClue(BasicConstant.ONE));
                            initPojo.setAppMenuFormIdPojoList(appMenuFormIdPojos);
                        }
                        // 特殊标识，图表中心客户阶段漏斗
                        initPojo.setSpecialParam("clueSource");
                    }
                } else if (statisticsTypeEnum == StatisticsTypeEnum.CUSTOM_STATISTIC) {
                    setCustomLineChartData(entity, chartResultVO);
                }
                break;
            // 饼图
            case PIE_CHART:
                // 系统指标
                if (statisticsTypeEnum == StatisticsTypeEnum.SYSTEM_STATISTIC) {
                    // 只添加图，平台设置为dingtalk
                    setFunnelOrPieChartData(entity, chartResultVO, StringConstant.PLATFORM_DINGTALK, initPojo, mutilTemplateFormMap);
                } else if (statisticsTypeEnum == StatisticsTypeEnum.CUSTOM_STATISTIC) {
                    setFunnelOrPieChartData(entity, chartResultVO, StringConstant.PLATFORM_DINGTALK, initPojo, mutilTemplateFormMap);
                }
                break;
            // 雷达图
            case RADAR_CHART:
                // 系统指标
                // TODO 统计未实现，无具体格式
                if (statisticsTypeEnum == StatisticsTypeEnum.SYSTEM_STATISTIC) {
                    // 只添加图，平台设置为dingtalk
                    setRadarChartData(entity, chartResultVO);
                } else if (statisticsTypeEnum == StatisticsTypeEnum.CUSTOM_STATISTIC) {
                    setRadarChartData(entity, chartResultVO);
                }
                break;
            // 面积图
            case AREA_CHART:
                // 系统指标
                if (statisticsTypeEnum == StatisticsTypeEnum.SYSTEM_STATISTIC) {
                    // 只添加图，平台设置为dingtalk
                    setLineChartData(entity, chartResultVO, StringConstant.PLATFORM_DINGTALK);
                } else if (statisticsTypeEnum == StatisticsTypeEnum.CUSTOM_STATISTIC) {
                    setCustomLineChartData(entity, chartResultVO);
                }
                break;
            // 漏斗图
            case FUNNEL_COMMON:
            case FUNNEL_COMPLEX:
                // 系统指标
                if (statisticsTypeEnum == StatisticsTypeEnum.SYSTEM_STATISTIC) {
                    // 只添加图，平台设置为dingtalk
                    setFunnelOrPieChartData(entity, chartResultVO, StringConstant.PLATFORM_DINGTALK, initPojo, mutilTemplateFormMap);
                }
                break;
            // 地图
            case MAP:
                // 系统指标
                if (statisticsTypeEnum == StatisticsTypeEnum.SYSTEM_STATISTIC) {
                    // 只添加图，平台设置为dingtalk
                    setMapChartData(entity, chartResultVO);
                }
                break;
            case PIE_RING:
                if (Objects.equals(entity.getSystemCode(), SystemCodeEnum.CLUE_SOURCE.getSystemCode()) || Objects.equals(entity.getSystemCode(), SystemCodeEnum.CLUE_INVALID_RESOURCE.getSystemCode())) {
                    List<AppMenuFormIdPojo> appMenuFormIdPojos = (List<AppMenuFormIdPojo>) CloneUtil.deepClone(mutilTemplateFormMap.get(XbbRefTypeEnum.CLUE.getCode()));
                    if (CollectionsUtil.isNotEmpty(appMenuFormIdPojos)) {
                        appMenuFormIdPojos.forEach(item -> item.setSourceClue(BasicConstant.ONE));
                        initPojo.setAppMenuFormIdPojoList(appMenuFormIdPojos);
                    }
                    // 特殊标识，图表中心客户阶段漏斗
                    initPojo.setSpecialParam("clueSource");
                }
            default:
                break;
        }
        JSONArray childList = new JSONArray();
        childList.add(chartResultVO);
        initPojo.setChildList(childList);

        return initPojo;
    }

    /**
     * 是否简报看板
     *
     * @param alias 别名
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-19 11:20
     * @version v1.0
     * @since v1.0
     */
    private boolean isReportBoard(String alias) {
        return ChartCategoryAliasEnum.REPORT_BOARD.getAlias().equals(alias);
    }

    /**
     * 是否遗忘提醒/客户关怀看板
     *
     * @param alias 别名
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-20 15:14
     * @version v1.0
     * @since v1.0
     */
    private boolean isForgetOrCareBoard(String alias) {
        return ChartCategoryAliasEnum.FORGET_REMIND.getAlias().equals(alias) ||
                ChartCategoryAliasEnum.CUSTOMER_CARE.getAlias().equals(alias);
    }

    private boolean isFundBoard(String alias) {
        return ChartCategoryAliasEnum.FUND_MANAGEMENT.getAlias().equals(alias);
    }

    /**
     * 是否系统统计看板（客户/合同/回款/付款/采购/工单）
     *
     * @param alias 别名
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-19 11:20
     * @version v1.0
     * @since v1.0
     */
    private boolean isSystemChartBoard(String alias) {
        return ChartCategoryAliasEnum.CUSTOMER.getAlias().equals(alias) ||
                ChartCategoryAliasEnum.CONTRACT.getAlias().equals(alias) ||
                ChartCategoryAliasEnum.PAYMENT.getAlias().equals(alias) ||
                ChartCategoryAliasEnum.PAY.getAlias().equals(alias) ||
                ChartCategoryAliasEnum.PURCHASE.getAlias().equals(alias) ||
                ChartCategoryAliasEnum.WORK_ORDER.getAlias().equals(alias) ||
                ChartCategoryAliasEnum.QUOTATION.getAlias().equals(alias) ||
                ChartCategoryAliasEnum.SALE_CLUE_CHART.getAlias().equals(alias);
    }

    /**
     * 是否销售机会看板
     *
     * @param alias 别名
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-19 11:20
     * @version v1.0
     * @since v1.0
     */
    private boolean isOpportunityBoard(String alias) {
        return ChartCategoryAliasEnum.OPPORTUNITY.getAlias().equals(alias);
    }

    /**
     * 是否业绩目标看板
     *
     * @param alias 别名
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-19 11:20
     * @version v1.0
     * @since v1.0
     */
    private boolean isPerformanceBoard(String alias) {
        return ChartCategoryAliasEnum.PERFORMANCE.getAlias().equals(alias);
    }

    /**
     * 是否pk看板
     *
     * @param alias 别名
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-19 11:20
     * @version v1.0
     * @since v1.0
     */
    private boolean isPkBoard(String alias) {
        return ChartCategoryAliasEnum.PK.getAlias().equals(alias);
    }

    /**
     * 是否右侧看板
     * web:公告，销售简报，待处理审批，审批进展，待处理工单，访客计划，跟进提醒，库存预警，客服
     * app:销售简报，待处理审批，审批进展，待处理工单，访客计划，跟进提醒，库存预警
     *
     * @param alias 别名
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-19 11:20
     * @version v1.0
     * @since v1.0
     */
    private boolean isRightBoard(String alias, String platform) {
        if (StringConstant.PLATFORM_WEB.equals(platform)) {
            // 公告，销售简报，待处理审批，审批进展，待处理工单，访客计划，跟进提醒，库存预警，客服,数据预警
            return ChartCategoryAliasEnum.ANNOUNCEMENT.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.SALES_REPORT.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.APPROVAL.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.APPROVAL_PROGRESS.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.PENDING_WORK_ORDER.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.PENDING_WORK_ORDER_V2.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.COMMUNICATE_PLAN.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.REMIND.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.STOCK_WARNING.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.KE_FU.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.DATA_WARNING.getAlias().equals(alias)||
                    ChartCategoryAliasEnum.FORGET_REMIND.getAlias().equals(alias)||
                    ChartCategoryAliasEnum.CUSTOMER_CARE.getAlias().equals(alias);
        } else if (StringConstant.PLATFORM_DINGTALK.equals(platform)) {
            // 销售简报，待处理审批，审批进展，待处理工单，访客计划，跟进提醒，库存预警,数据预警
            return ChartCategoryAliasEnum.SALES_REPORT.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.APPROVAL.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.APPROVAL_PROGRESS.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.PENDING_WORK_ORDER.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.PENDING_WORK_ORDER_V2.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.COMMUNICATE_PLAN.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.REMIND.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.STOCK_WARNING.getAlias().equals(alias) ||
                    ChartCategoryAliasEnum.DATA_WARNING.getAlias().equals(alias)||
                    ChartCategoryAliasEnum.FORGET_REMIND.getAlias().equals(alias);
        }
        return false;
    }

    @Override
    public List<String> getDingTalkRightAlias(){
        List<String> aliasList = new ArrayList<>();
        aliasList.add(ChartCategoryAliasEnum.SALES_REPORT.getAlias());
        aliasList.add(ChartCategoryAliasEnum.APPROVAL.getAlias());
        aliasList.add(ChartCategoryAliasEnum.APPROVAL_PROGRESS.getAlias());
        aliasList.add(ChartCategoryAliasEnum.PENDING_WORK_ORDER.getAlias());
        aliasList.add(ChartCategoryAliasEnum.PENDING_WORK_ORDER_V2.getAlias());
        aliasList.add(ChartCategoryAliasEnum.COMMUNICATE_PLAN.getAlias());
        aliasList.add(ChartCategoryAliasEnum.REMIND.getAlias());
        aliasList.add(ChartCategoryAliasEnum.STOCK_WARNING.getAlias());
        aliasList.add(ChartCategoryAliasEnum.DATA_WARNING.getAlias());
        aliasList.add(ChartCategoryAliasEnum.FORGET_REMIND.getAlias());
        return aliasList;
    }

    @Override
    public Integer deleteFocusBatchByCorpids4Script(List<String> list) {
        List<Integer> boardList = new ArrayList<>();
        boardList.add(BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode());
        boardList.add(BoardTypeEnum.FOCUS_DINGTALK_WORK.getCode());
        return indexSetModel.deleteFocusBatchByCorpids4Script(list,boardList);
    }

    /**
     * 是否有展示方式筛选项
     *
     * @param showTypes 展示方式列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-19 11:26
     * @version v1.0
     * @since v1.0
     */
    private boolean hasShowTypes(JSONArray showTypes) {
        if (showTypes == null || showTypes.size() == 0) {
            return false;
        }
        // 柱形图,折线图，机会漏斗
        return showTypes.contains(ChartTypeEnum.BAR_CHART.getCode()) ||
                showTypes.contains(ChartTypeEnum.LINE_CHART.getCode()) ||
                showTypes.contains(ChartTypeEnum.FUNNEL_COMMON.getCode());
    }

    /**
     * 封装（app-设置）展示数据
     *
     * @param setList      设置列表
     * @param companyData  分类、图表信息
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-20 15:46
     * @version v1.0
     * @since v1.0
     */
    private List<IndexBoardGetConfigAppPojo> formatConfigApp(List<IndexSetDataPojo> setList, ChartCategoryInitVO companyData,Boolean isFocus) {
        if (setList == null || setList.size() == 0) {
            return new ArrayList<>();
        }
        List<IndexBoardGetConfigAppPojo> list = new ArrayList<>();
        Map<Long, ChartCategoryEntity> categoryMap = companyData.getCategoryMap();
//        TODO 和线上逻辑保持一致，也用既包含系统、又包含自定义图表的map
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        int maxSort = -1;
        int communicateIndex = 0;
        IndexBoardGetConfigAppPojo communicatePlanPojo = null;
        for (IndexSetDataPojo dataPojo : setList) {
            Long id = dataPojo.getChartCategoryId();
            int chartCategoryType = dataPojo.getChartCategoryType();
            IndexBoardGetConfigAppPojo pojo = new IndexBoardGetConfigAppPojo();
            String name = "";
            if (chartCategoryType == ChartConstant.CHART_CATEGORY_TYPE_CATEGORY ) {
                if (!categoryMap.containsKey(id)) {
                    continue;
                }
                // 过虑库存预警
                if (Objects.equals(ChartCategoryAliasEnum.STOCK_WARNING.getAlias(), categoryMap.get(id).getAlias())) {
                    continue;
                }
                name = categoryMap.get(id).getName();
            } else if (chartCategoryType == ChartConstant.CHART_CATEGORY_TYPE_CHART) {
//                TODO 此处使用需在宏晓改造后改掉 - 根据具体statisticsType读取
                ChartEntity chartEntity = customChartMap.get(id);
                if (Objects.isNull(chartEntity)) {
                    chartEntity = systemChartMap.get(id);
                }
                if (Objects.isNull(chartEntity)) {
                    continue;
                }
                name = chartEntity.getName();
            }
            BeanUtil.copyProperties(dataPojo, pojo);
            pojo.setName(name);
            // 访客计划设置置灰置顶,有权限看到就开启
            if (chartCategoryType == ChartConstant.CHART_CATEGORY_TYPE_CATEGORY && Objects.equals(ChartCategoryAliasEnum.COMMUNICATE_PLAN.getAlias(), categoryMap.get(id).getAlias())) {
                pojo.setEnable(1);
                pojo.setForbidden(PaasConstant.ENABLE_FORBIDDEN);
                if (!isFocus){
                    pojo.setHidden(PaasConstant.ENABLE_HIDDEN);
                }
                communicatePlanPojo = pojo;
                communicateIndex = list.size();
            }
            if (null != pojo.getSort() && pojo.getSort() > maxSort){
                maxSort = pojo.getSort();
            }
            list.add(pojo);
        }
        // 访客计划设置置顶
        if (null != communicatePlanPojo){
            communicatePlanPojo.setSort(++maxSort);
            list.remove(communicateIndex);
            list.add(0,communicatePlanPojo);
        }
        return list;
    }

    /**
     * 格式化简报看板数据
     *
     * @param setPojo   简报看板实体
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-11 10:54
     * @version v1.0
     * @since v1.0
     */
    private JSONArray formatReportBoard(IndexSetDataPojo setPojo, ChartCategoryInitVO companyData, List<Long> enableSystemIds, List<ChartIdPojo> chartIdPojoList) throws XbbException {
        JSONArray array = new JSONArray();
        List<ChartEntity> chartList = companyData.getChartList();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        if (chartList == null || chartList.size() <= 0) {
            return array;
        }
        boolean standardWithFeeType = marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(chartList.get(0).getCorpid());
        List<String> systemcode = Arrays.asList(SystemCodeEnum.CLUE_TOTAL_BOARD.getSystemCode(), SystemCodeEnum.CLUE_ADD_BOARD.getSystemCode(), SystemCodeEnum.CLUE_FOLLOW_BOARD.getSystemCode());
        List<IndexBoardChartSavePojo> enableList = setPojo.getEnableList();
        if (enableList == null || enableList.size() == 0) {
            return array;
        }
        for (ChartEntity entity : chartList) {
            //  旗舰版未开通                  标准版不展示
            if (systemcode.contains(entity.getSystemCode()) && standardWithFeeType) {
                continue;
            }
        }

        // 排序
        enableList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());


        // 清空enableIds数据
        enableSystemIds.clear();
        chartIdPojoList.clear();

        for (IndexBoardChartSavePojo savePojo : enableList) {
            // 超过12个，后面的不显示
            if ((chartIdPojoList.size()) == CHART_MAX_COUNT) {
                break;
            }
            ChartEntity entity;
            if (Objects.equals(savePojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                entity = customChartMap.get(savePojo.getId());
            } else {
                entity = systemChartMap.get(savePojo.getId());
            }
            if (entity == null) {
                continue;
            }
            // 旗舰版未开通                  标准版不展示
            if (systemcode.contains(entity.getSystemCode()) && standardWithFeeType) {
                continue;
            }
            ChartResultValueDetailVO reportBoardPojo = new ChartResultValueDetailVO();
            BeanUtil.copyProperties(entity, reportBoardPojo);
            // 默认值
            reportBoardPojo.setValue("0");
            reportBoardPojo.setThrough("");
            array.add(reportBoardPojo);
            ChartIdPojo chartIdPojo = new ChartIdPojo();
            chartIdPojo.setId(entity.getId());
            chartIdPojo.setStatisticsType(entity.getStatisticsType());
            chartIdPojoList.add(chartIdPojo);
            if (Objects.equals(entity.getStatisticsType(), StatisticsTypeEnum.SYSTEM_STATISTIC.getCode())) {
                enableSystemIds.add(entity.getId());
            }
        }

        return array;
    }

    /**
     * 格式化资金管理看板数据
     *
     * @param setPojo 简报看板实体
     * @return com.alibaba.fastjson.JSONArray
     * @throws
     * @author 徐俊杰
     * @date 2020/3/14 9:48
     * @since v1.0
     */
    private JSONArray formatFundManagement(IndexSetDataPojo setPojo, ChartCategoryInitVO companyData, List<Long> enableSystemIds, List<ChartIdPojo> chartIdPojoList) {
        JSONArray array = new JSONArray();
        List<ChartEntity> chartList = companyData.getChartList();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        if (chartList == null || chartList.size() <= 0) {
            return array;
        }

        List<IndexBoardChartSavePojo> enableList = setPojo.getEnableList();
        if (enableList == null || enableList.size() == 0) {
            return array;
        }

        // 排序
        enableList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());

        // 清空enableIds数据
        enableSystemIds.clear();
        chartIdPojoList.clear();

        for (IndexBoardChartSavePojo savePojo : enableList) {
            ChartEntity entity;
            if (Objects.equals(savePojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                entity = customChartMap.get(savePojo.getId());
            } else {
                entity = systemChartMap.get(savePojo.getId());
            }
            if (entity == null) {
                continue;
            }

            ChartResultValueDetailVO reportBoardPojo = new ChartResultValueDetailVO();
            BeanUtil.copyProperties(entity, reportBoardPojo);
            ChartResultUtil.dealWithGroupIconColor(reportBoardPojo, SystemCodeEnum.getByCode(entity.getSystemCode()));
            // 默认值
            reportBoardPojo.setValue("0");
            reportBoardPojo.setThrough("");
            array.add(reportBoardPojo);

            ChartIdPojo chartIdPojo = new ChartIdPojo();
            chartIdPojo.setId(entity.getId());
            chartIdPojo.setStatisticsType(entity.getStatisticsType());
            chartIdPojoList.add(chartIdPojo);
            if (Objects.equals(entity.getStatisticsType(), StatisticsTypeEnum.SYSTEM_STATISTIC.getCode())) {
                enableSystemIds.add(entity.getId());
            }
        }

        return array;
    }

    /**
     * 格式系统图表数据
     *
     * @param setPojo   设置实体
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-14 21:14
     * @version v1.0
     * @since v1.0
     */
    private JSONArray formatSystemChartData(IndexSetDataPojo setPojo, ChartCategoryInitVO companyData, String platform) {
        JSONArray array = new JSONArray();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        if (systemChartMap.size() <= 0 && customChartMap.size() <= 0) {
            return array;
        }

        List<IndexBoardChartSavePojo> enableList = setPojo.getEnableList();
        if (enableList == null || enableList.size() == 0) {
            return array;
        }

        // 排序
        enableList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        for (IndexBoardChartSavePojo savePojo : enableList) {
            ChartEntity entity;
            if (Objects.equals(savePojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                entity = customChartMap.get(savePojo.getId());
            } else {
                entity = systemChartMap.get(savePojo.getId());
            }
            if (entity == null) {
                continue;
            }
            // 展示方式
            int chartType = entity.getChartType();

            ChartResultDetailVO chartResultVO = new ChartResultDetailVO();
            chartResultVO.setChartId(entity.getId());
            // 是否显示table及chart是否展示xAxis等值（展示方式：柱形图、折线图、表格）
            if (ChartTypeEnum.VALUE.getCode() == chartType) {
                ResultChartVO chartVO = new ResultChartVO();
                BeanUtil.copyProperties(entity, chartVO);
                chartVO.setValue("0");
                List<ResultChartVO> chartVOList = Arrays.asList(chartVO);
                chartResultVO.setChart(chartVOList);
                chartResultVO.setTable(null);
            } else {
                setLineChartData(entity, chartResultVO, platform);
            }

            array.add(chartResultVO);
        }

        return array;
    }

    /**
     * 格式化销售机会图表数据
     *
     * @param setPojo   简报看板实体
     * @param platform  平台
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-20 16:08
     * @version v1.0
     * @since v1.0
     */
    private JSONArray formatOpportunityData(IndexSetDataPojo setPojo, ChartCategoryInitVO companyData, String platform, Long formId) {
        JSONArray array = new JSONArray();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        if (systemChartMap.size() <= 0 && customChartMap.size() <= 0) {
            return array;
        }

        List<IndexBoardChartSavePojo> enableList = setPojo.getEnableList();
        if (enableList == null || enableList.size() == 0) {
            return array;
        }


        // 排序
        enableList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        for (IndexBoardChartSavePojo savePojo : enableList) {
            ChartEntity entity;
            if (Objects.equals(savePojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                entity = customChartMap.get(savePojo.getId());
            } else {
                entity = systemChartMap.get(savePojo.getId());
            }
            if (entity == null) {
                continue;
            }
            // 展示方式
            int chartType = entity.getChartType();

            ChartResultDetailVO chartResultVO = new ChartResultDetailVO();
            chartResultVO.setChartId(entity.getId());
            // table及chart处理（普通漏斗，表格）

            if (ChartTypeEnum.VALUE.getCode() == chartType) {
                ResultChartVO chartVO = new ResultChartVO();
                BeanUtil.copyProperties(entity, chartVO);
                List<ResultChartVO> chartVOList = Arrays.asList(chartVO);
                chartResultVO.setChart(chartVOList);
                chartResultVO.setTable(null);
            } else {
                setOppFunnelChartData(entity, chartResultVO, platform, formId);
            }

            array.add(chartResultVO);
        }

        return array;
    }

    /**
     * 系统默认：设置图表上展示数据（线性图、柱状图、表格）
     *
     * @param entity        指标实体
     * @param chartResultVO 展示数据
     * @param platform      平台
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-14 21:16
     * @version v1.0
     * @since v1.0
     */
    private void setLineChartData(ChartEntity entity, ChartResultDetailVO chartResultVO, String platform) {
        ResultChartVO chartVO = new ResultChartVO();
        BeanUtil.copyProperties(entity, chartVO);
        String name = entity.getName();
        Integer count = dateTitleList.size();
        List<String> xAxis = dateTitleList;
        List<String> legend = Arrays.asList(name);
        boolean totalFlag = false;
        String value = "0";
        String valueTitle = "";
        JSONArray valueArray = new JSONArray();
        for (int i = 0; i < count; i++) {
            valueArray.add("0");
        }
        ResultDataChartVO dataChartVO = new ResultDataChartVO(name, null, valueArray);
        List<ResultDataChartVO> data = new ArrayList<>();
        data.add(dataChartVO);
        List<ResultDataSeriesChartVO> dataSerie = null;
        chartVO.setXAxis(xAxis);
        chartVO.setLegend(legend);
        chartVO.setTotalFlag(totalFlag);
        chartVO.setValue(value);
        chartVO.setValueTitle(valueTitle);
        chartVO.setData(data);
        chartVO.setDataSeries(dataSerie);
        List<ResultChartVO> chartVOList = Arrays.asList(chartVO);
        chartResultVO.setChart(chartVOList);

        // resultTable处理(只有web端有表格，app端没有表格）
        if (StringConstant.PLATFORM_WEB.equals(platform)) {
            ResultTableVO tableVO = new ResultTableVO();
            String headMemo = "";
            List<String> title = new ArrayList<>();
            title.add(I18nMessageUtil.getMessage(CommonConstant.TIME));
            title.addAll(dateTitleList);

            List<List<ResultDataTableVO>> tableData = new ArrayList<>();
            List<ResultDataTableVO> tableDataValueList = new ArrayList<>();
            for (int i = 0; i < title.size(); i++) {
                String tableValue = i == 0 ? name : "0";
                String through = i == 0 ? null : "";
                ResultDataTableVO dataTableVO = new ResultDataTableVO(tableValue, through);
                tableDataValueList.add(dataTableVO);
            }
            tableData.add(tableDataValueList);

            PageHelper pageHelper = null;
            tableVO.setHeadMemo(headMemo);
            tableVO.setTitle(systemChartHelp.titleNumRight(title));
            tableVO.setData(tableData);
            tableVO.setPageHelper(pageHelper);
            chartResultVO.setTable(tableVO);
        }
    }

    /**
     * 发送到首页：设置图表上展示数据（线性图、柱状图、表格）
     *
     * @param entity        指标实体
     * @param chartResultVO 展示数据
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-30 16:01
     * @version v1.0
     * @since v1.0
     */
    private void setCustomLineChartData(ChartEntity entity, ChartResultDetailVO chartResultVO) {
        ResultChartVO chartVO = new ResultChartVO();
        BeanUtil.copyProperties(entity, chartVO);
        String name = entity.getName();
        // x轴数据
        List<String> xAxis = new ArrayList<>();
        JSONArray chartClassifyArray = entity.getChartClassify();
        Integer count = chartClassifyArray.size();
        // TODO 等鲁江的pojo出来后，替换这部分代码
//        for (Object object : chartClassifyArray) {
//            JSONObject jsonObject = (JSONObject) object;
//            xAxis.add(jsonObject.getString("attr"));
//        }
        // TODO 等鲁江的pojo出来后，替换这部分代码
        List<String> legend = new ArrayList<>();
//        for (Object object : entity.getChartSeries()) {
//            JSONObject jsonObject = (JSONObject) object;
//            legend.add(jsonObject.getString("attr"));
//        }

        boolean totalFlag = false;
        String value = "0";
        String valueTitle = "";
        JSONArray valueArray = new JSONArray();
        for (int i = 0; i < count; i++) {
            valueArray.add("0");
        }
        ResultDataChartVO dataChartVO = new ResultDataChartVO(name, null, valueArray);
        List<ResultDataChartVO> data = new ArrayList<>();
        data.add(dataChartVO);
        List<ResultDataSeriesChartVO> dataSerie = null;
        chartVO.setXAxis(xAxis);
        chartVO.setLegend(legend);
        chartVO.setTotalFlag(totalFlag);
        chartVO.setValue(value);
        chartVO.setValueTitle(valueTitle);
        chartVO.setData(data);
        chartVO.setDataSeries(dataSerie);
        List<ResultChartVO> chartVOList = Arrays.asList(chartVO);
        chartResultVO.setChart(chartVOList);
    }

    /**
     * 设置漏斗和表格展示数据
     *
     * @param entity        数据实体
     * @param chartResultVO 展示实体
     * @param platform      平台
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-15 21:47
     * @version v1.0
     * @since v1.0
     */
    private void setOppFunnelChartData(ChartEntity entity, ChartResultDetailVO chartResultVO, String platform, Long formId) {
        StageFindStrategy stageFindStrategy = StageFindFactory.getStageFindStrategy(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
        Long stageProcessId = stageFindStrategy.getNowProcessId(entity.getCorpid(), formId);
        List<? extends PaasStageEntity> stageList = stageFindStrategy.findStageListSpecial
                (entity.getCorpid(), new StageFindPojo(formId, stageProcessId));
        ResultChartVO chartVO = new ResultChartVO();
        BeanUtil.copyProperties(entity, chartVO);
        boolean totalFlag = false;
        String value = "0";
        String valueTitle = "";
        NumFormatEnum numFormatEnum = NumFormatEnum.getByCode(entity.getNumFormat());

        List<ResultDataSeriesChartVO> dataSerie = new ArrayList<>();
        // table数据
        List<List<ResultDataTableVO>> tableData = new ArrayList<>();
        // table数据处理
        List<ResultDataTableVO> tableDataValueList = new ArrayList<>();
        for (PaasStageEntity stageEntity : stageList) {
            String realName = stageEntity.getName();
            String name = realName + I18nMessageUtil.getMessage(I18nStringConstant.ZERO);
            ResultDataSeriesChartVO seriesChartVO = new ResultDataSeriesChartVO(name, realName, stageEntity.getCode().toString(), "0");
            dataSerie.add(seriesChartVO);

            ResultDataTableVO dataTableVO1 = new ResultDataTableVO(stageEntity.getName(), null);
            ResultDataTableVO dataTableVO2 = new ResultDataTableVO("0", "");
            ResultDataTableVO dataTableVO3 = new ResultDataTableVO("0", "");
            tableDataValueList.add(dataTableVO1);
            tableDataValueList.add(dataTableVO2);
            tableDataValueList.add(dataTableVO3);
        }
        tableData.add(tableDataValueList);

        chartVO.setXAxis(null);
        chartVO.setLegend(null);
        chartVO.setTotalFlag(totalFlag);
        chartVO.setValue(value);
        chartVO.setValueTitle(valueTitle);
        chartVO.setData(null);
        chartVO.setDataSeries(dataSerie);
        List<ResultChartVO> chartVOList = Arrays.asList(chartVO);
        chartResultVO.setChart(chartVOList);

        // resultTable处理(只有web端有表格，app端没有表格）
        if (StringConstant.PLATFORM_WEB.equals(platform)) {
            ResultTableVO tableVO = new ResultTableVO();
            String headMemo = "";
            List<String> title = Arrays.asList("机会阶段", "数量/个", "金额/" + numFormatEnum.getUnit());


            PageHelper pageHelper = null;
            tableVO.setHeadMemo(headMemo);
            tableVO.setTitle(systemChartHelp.titleNumRight(title));
            tableVO.setData(tableData);
            tableVO.setPageHelper(pageHelper);
            chartResultVO.setTable(tableVO);
        }
    }

    /**
     * 设置漏斗/饼图和表格展示数据
     *
     * @param entity        数据实体
     * @param chartResultVO 展示实体
     * @param platform      平台
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-05-07 20:38
     * @version v1.0
     * @since v1.0
     */
    private void setFunnelOrPieChartData(ChartEntity entity, ChartResultDetailVO chartResultVO, String platform, IndexInitPojo initPojo, Map<Integer, List<AppMenuFormIdPojo>> mutilTemplateFormMap) {
        SystemCodeEnum systemCodeEnum = SystemCodeEnum.getByCode(entity.getSystemCode());
        if (Objects.equals(systemCodeEnum, SystemCodeEnum.CUSTOMER_FUNNEL_CHART)) {
            List<AppMenuFormIdPojo> appMenuFormIdPojoList = mutilTemplateFormMap.get(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            Long formId = null;
            if (CollectionsUtil.isNotEmpty(appMenuFormIdPojoList)) {
                AppMenuFormIdPojo appMenuFormIdPojo = appMenuFormIdPojoList.get(0);
                formId = appMenuFormIdPojo.getFormId();
                initPojo.setAppMenuFormIdPojoList(appMenuFormIdPojoList);
            }
            // 特殊标识，图表中心客户阶段漏斗
            initPojo.setSpecialParam("customerStage");
            setCustomerFunnel(entity, chartResultVO, platform, formId);
            return;
        } else  if (Objects.equals(systemCodeEnum, SystemCodeEnum.CLUE_STAGE) || Objects.equals(systemCodeEnum, SystemCodeEnum.CLUE_CONVERSION_CHART) || Objects.equals(systemCodeEnum, SystemCodeEnum.CLUE_SOURCE)){
            List<AppMenuFormIdPojo> appMenuFormIdPojoList = mutilTemplateFormMap.get(XbbRefTypeEnum.CLUE.getCode());
            Long formId = null;
            if (CollectionsUtil.isNotEmpty(appMenuFormIdPojoList)) {
                AppMenuFormIdPojo appMenuFormIdPojo = appMenuFormIdPojoList.get(0);
                formId = appMenuFormIdPojo.getFormId();
                initPojo.setAppMenuFormIdPojoList(appMenuFormIdPojoList);
            }
            // 特殊标识，图表中心客户阶段漏斗
            initPojo.setSpecialParam("clueBoard");
            setCustomerFunnel(entity, chartResultVO, platform, formId);
            return;
        }

        ResultChartVO chartVO = new ResultChartVO();
        BeanUtil.copyProperties(entity, chartVO);
        boolean totalFlag = false;
        String value = "0";
        String valueTitle = "";

        List<ResultDataSeriesChartVO> dataSerie = new ArrayList<>();
        // table数据
        List<List<ResultDataTableVO>> tableData = new ArrayList<>();
        // table数据处理
        List<ResultDataTableVO> tableDataValueList = new ArrayList<>();
        // 只设置一个数据

        String realName = I18nMessageUtil.getMessage(CommonConstant.STAGE);
        String name = realName + I18nMessageUtil.getMessage(I18nStringConstant.ZERO);
        ResultDataSeriesChartVO seriesChartVO = new ResultDataSeriesChartVO(name, realName, "1", "0");
        dataSerie.add(seriesChartVO);

        ResultDataTableVO dataTableVO1 = new ResultDataTableVO(realName, null);
        ResultDataTableVO dataTableVO2 = new ResultDataTableVO("0", "");
        ResultDataTableVO dataTableVO3 = new ResultDataTableVO("0", "");
        tableDataValueList.add(dataTableVO1);
        tableDataValueList.add(dataTableVO2);
        tableDataValueList.add(dataTableVO3);

        tableData.add(tableDataValueList);

        chartVO.setXAxis(null);
        chartVO.setLegend(null);
        chartVO.setTotalFlag(totalFlag);
        chartVO.setValue(value);
        chartVO.setValueTitle(valueTitle);
        chartVO.setData(null);
        chartVO.setDataSeries(dataSerie);
        List<ResultChartVO> chartVOList = Arrays.asList(chartVO);
        chartResultVO.setChart(chartVOList);

        // resultTable处理(只有web端有表格，app端没有表格）
        if (StringConstant.PLATFORM_WEB.equals(platform)) {
            ResultTableVO tableVO = new ResultTableVO();
            String headMemo = "";
            List<String> title = Arrays.asList("阶段", "数量/个", "金额/元");

            PageHelper pageHelper = null;
            tableVO.setHeadMemo(headMemo);
            tableVO.setTitle(systemChartHelp.titleNumRight(title));
            tableVO.setData(tableData);
            tableVO.setPageHelper(pageHelper);
            chartResultVO.setTable(tableVO);
        }
    }

    private void setCustomerFunnel(ChartEntity entity, ChartResultDetailVO chartResultVO, String platform, Long formId) {
        ResultChartVO chartVO = new ResultChartVO();
        BeanUtil.copyProperties(entity, chartVO);
        boolean totalFlag = false;
        String value = "0";
        String valueTitle = "";

        StageFindStrategy stageFindStrategy = StageFindFactory.getStageFindStrategy(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        Long stageProcessId = stageFindStrategy.getNowProcessId(entity.getCorpid(), formId);
        List<? extends PaasStageEntity> saleStageList = stageFindStrategy.findStageListSpecial(entity.getCorpid(), new StageFindPojo(formId, stageProcessId));

        List<ResultDataSeriesChartVO> dataSerie = new ArrayList<>();
        // table数据
        List<List<ResultDataTableVO>> tableData = new ArrayList<>();
        // table数据处理
        List<ResultDataTableVO> tableDataValueList = new ArrayList<>();
        for (PaasStageEntity stageEntity : saleStageList) {
            String realName = stageEntity.getName();
            String name = realName + I18nMessageUtil.getMessage(I18nStringConstant.ZERO);
            ResultDataSeriesChartVO seriesChartVO = new ResultDataSeriesChartVO(name, realName, stageEntity.getCode().toString(), "0");
            dataSerie.add(seriesChartVO);

            ResultDataTableVO dataTableVO1 = new ResultDataTableVO(realName, null);
            ResultDataTableVO dataTableVO2 = new ResultDataTableVO("0", "");
            ResultDataTableVO dataTableVO3 = new ResultDataTableVO("0", "");
            tableDataValueList.add(dataTableVO1);
            tableDataValueList.add(dataTableVO2);
            tableDataValueList.add(dataTableVO3);
        }
        tableData.add(tableDataValueList);

        chartVO.setXAxis(null);
        chartVO.setLegend(null);
        chartVO.setTotalFlag(totalFlag);
        chartVO.setValue(value);
        chartVO.setValueTitle(valueTitle);
        chartVO.setData(null);
        chartVO.setDataSeries(dataSerie);
        List<ResultChartVO> chartVOList = Arrays.asList(chartVO);
        chartResultVO.setChart(chartVOList);

        // resultTable处理(只有web端有表格，app端没有表格）
        if (StringConstant.PLATFORM_WEB.equals(platform)) {
            ResultTableVO tableVO = new ResultTableVO();
            String headMemo = "";
            List<String> title = Arrays.asList("阶段", "数量/个", "金额/元");

            PageHelper pageHelper = null;
            tableVO.setHeadMemo(headMemo);
            tableVO.setTitle(systemChartHelp.titleNumRight(title));
            tableVO.setData(tableData);
            tableVO.setPageHelper(pageHelper);
            chartResultVO.setTable(tableVO);
        }
    }

    /**
     * 格式化业绩目标展示数据
     *
     * @param setPojo   展示实体
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-30 15:59
     * @version v1.0
     * @since v1.0
     */
    private JSONArray formatPerformanceData(IndexSetDataPojo setPojo, ChartCategoryInitVO companyData, List<Long> enableSystemIds, List<ChartIdPojo> chartIdPojoList) throws XbbException {
        JSONArray array = new JSONArray();
        List<ChartEntity> chartList = companyData.getChartList();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        if (chartList == null || chartList.size() <= 0) {
            return array;
        }

        List<IndexBoardChartSavePojo> enableList = setPojo.getEnableList();
        if (enableList == null || enableList.size() == 0) {
            return array;
        }


        enableList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        // 清空ids
        enableSystemIds.clear();
        chartIdPojoList.clear();

        Boolean ultimateWithFeeType = packageHelp.isUltimateWithFeeType(chartList.get(0).getCorpid());
        for (IndexBoardChartSavePojo savePojo : enableList) {
            ChartEntity entity;
            if (Objects.equals(savePojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                // 判断套餐,如果不是旗舰版不显示自定义目标
                if (!ultimateWithFeeType){
                    entity = null;
                }else {
                    entity = customChartMap.get(savePojo.getId());
                }
            } else {
                entity = systemChartMap.get(savePojo.getId());
            }
            if (entity == null) {
                continue;
            }

            ChartResultPkDetailVO detailVO = new ChartResultPkDetailVO();
            detailVO.setId(entity.getId());
            detailVO.setChartType(entity.getChartType());
            detailVO.setStatisticsType(entity.getStatisticsType());

            // 一条数据
            PkPerforInfoPojo perforInfoPojo = new PkPerforInfoPojo();
            BeanUtil.copyProperties(entity, perforInfoPojo);
            perforInfoPojo.setFinish("0");
            perforInfoPojo.setTarget("0");
            perforInfoPojo.setRate("0");
            perforInfoPojo.setThrough("");

            detailVO.setPerforData(Collections.singletonList(perforInfoPojo));
            array.add(detailVO);

            ChartIdPojo chartIdPojo = new ChartIdPojo();
            chartIdPojo.setId(entity.getId());
            chartIdPojo.setStatisticsType(entity.getStatisticsType());
            chartIdPojoList.add(chartIdPojo);
            enableSystemIds.add(entity.getId());
        }

        return array;
    }

    /**
     * 格式化pk榜展示数据
     *
     * @param setPojo   展示实体
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-28 15:46
     * @version v1.0
     * @since v1.0
     */
    private JSONArray formatPkData(IndexSetDataPojo setPojo, ChartCategoryInitVO companyData, List<Long> enableSystemIds, List<ChartIdPojo> chartIdPojoList) {
        JSONArray array = new JSONArray();
        List<ChartEntity> chartList = companyData.getChartList();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        if (chartList == null || chartList.size() <= 0) {
            return array;
        }

        List<IndexBoardChartSavePojo> enableList = setPojo.getEnableList();
        if (enableList == null || enableList.size() == 0) {
            return array;
        }


        // 排序
        enableList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        // 清空ids
        enableSystemIds.clear();
        chartIdPojoList.clear();
        for (IndexBoardChartSavePojo savePojo : enableList) {
            ChartEntity entity;
            if (Objects.equals(savePojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                entity = customChartMap.get(savePojo.getId());
            } else {
                entity = systemChartMap.get(savePojo.getId());
            }
            if (Objects.isNull(entity)) {
                continue;
            }

            ChartResultPkDetailVO pkPojo = new ChartResultPkDetailVO();
            BeanUtil.copyProperties(entity, pkPojo);
            List<PkInfoPojo> pkData = new ArrayList<>(3);
            // 添加三条数据
            PkInfoPojo infoPojo1 = new PkInfoPojo();
            PkInfoPojo infoPojo2 = new PkInfoPojo();
            PkInfoPojo infoPojo3 = new PkInfoPojo();
            infoPojo1.setAvatar("");
            infoPojo1.setId("1");
            infoPojo1.setName("张三");
            infoPojo1.setDepName("");
            infoPojo1.setRank(1);
            infoPojo1.setValue("0");
            infoPojo1.setThrough("");
            BeanUtil.copyProperties(infoPojo1, infoPojo2);
            BeanUtil.copyProperties(infoPojo1, infoPojo3);

            pkData.add(infoPojo1);
            pkData.add(infoPojo2);
            pkData.add(infoPojo3);

            pkPojo.setPkData(pkData);
            array.add(pkPojo);

            ChartIdPojo chartIdPojo = new ChartIdPojo();
            chartIdPojo.setId(entity.getId());
            chartIdPojo.setStatisticsType(entity.getStatisticsType());
            chartIdPojoList.add(chartIdPojo);
            // 前端处理不动，现在先改成直接取id，不判断是否为系统图表和自定义图表
            enableSystemIds.add(entity.getId());
//            if (Objects.equals(entity.getStatisticsType(), StatisticsTypeEnum.SYSTEM_STATISTIC.getCode())) {
//                enableSystemIds.add(entity.getId());
//            }
        }

        return array;
    }

    // 雷达图
    private void setRadarChartData(ChartEntity entity, ChartResultDetailVO resultDetailVO) {

    }

    // 地图
    private void setMapChartData(ChartEntity entity, ChartResultDetailVO resultDetailVO) {
        ResultChartVO chartVO = new ResultChartVO();
        BeanUtil.copyProperties(entity, chartVO);

        List<ResultChartVO> chartVOList = Arrays.asList(chartVO);
        resultDetailVO.setChart(chartVOList);
    }


    /**
     * 获取需要保存的配置数据
     *
     * @param dataList 配置数据
     * @param setList  看板配置列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-01 16:05
     * @version v1.0
     * @since v1.0
     */
    private List<IndexSetDataPojo> getEnableConfig(List<IndexSetDataPojo> setList, List<IndexBoardSaveItemPojo> dataList,
                                                   ChartCategoryInitVO companyData) {
        List<IndexSetDataPojo> list = new ArrayList<>();
        // 排序
        if (dataList == null || dataList.size() == 0) {
            return list;
        }
        Map<Long, ChartCategoryEntity> categoryMap = companyData.getCategoryMap();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();


        for (IndexBoardSaveItemPojo itemPojo : dataList) {
            // 分类id
            Long id = itemPojo.getChartCategoryId();
            // 分类类型：1系统类型，2指标类型
            int type = Objects.nonNull(itemPojo.getChartCategoryType()) ? itemPojo.getChartCategoryType() : BasicConstant.ONE;
            // 指标类型：1系统指标，2自定义指标
            int statisticsType = Objects.nonNull(itemPojo.getStatisticsType()) ? itemPojo.getStatisticsType() : BasicConstant.ONE;
            // 是否已存在
            boolean hasFlag = false;
            IndexSetDataPojo setDataPojo = new IndexSetDataPojo();
            for (IndexSetDataPojo dataPojo : setList) {
                if (null == dataPojo){
                    continue;
                }
                hasFlag = Objects.equals(id, dataPojo.getChartCategoryId()) && Objects.equals(type,dataPojo.getChartCategoryType())&& Objects.equals(statisticsType,dataPojo.getStatisticsType());
                if (hasFlag) {
                    setDataPojo = dataPojo;
                    break;
                }
            }
            // 看板不存在，添加数据
            if (!hasFlag) {

                int showType = ChartTypeEnum.VALUE.getCode();
                if (type == ChartConstant.CHART_CATEGORY_TYPE_CATEGORY) {
                    // 系统默认指标从分类枚举获取
                    ChartCategoryEntity entity = categoryMap.get(id);
                    ChartCategoryAliasEnum chartCategoryAliasEnum = ChartCategoryAliasEnum.getByAlias(entity.getAlias());
                    showType = Objects.isNull(chartCategoryAliasEnum) ? showType : chartCategoryAliasEnum.getShowType();
                } else if (type == ChartConstant.CHART_CATEGORY_TYPE_CHART) {
                    // 发送到首页的，从指标里获取
                    ChartEntity entity;
                    if (statisticsType == StatisticsTypeEnum.SYSTEM_STATISTIC.getCode()) {
                        entity = systemChartMap.get(id);
                    } else {
                        entity = customChartMap.get(id);
                    }
                    if (Objects.isNull(entity)) {
                        continue;
                    }
                    showType = entity.getChartType();
                    setDataPojo.setStatisticsType(entity.getStatisticsType());

                }

                setDataPojo.setChartCategoryId(id);
                setDataPojo.setChartCategoryType(type);
                // 展示类型
                setDataPojo.setShowType(showType);
            }
            // 前端需要
            setDataPojo.setAppHide(itemPojo.getAppHide());
            // 修改为启用
            setDataPojo.setEnable(BasicConstant.IS_USE);
            // 修改排序
            setDataPojo.setSort(itemPojo.getSort());
            // 二级分类id(跳转到图表中心，定位使用)
            if (itemPojo.getSecondCategoryId() != null) {
                setDataPojo.setSecondCategoryId(itemPojo.getSecondCategoryId());
            }
            list.add(setDataPojo);
        }
        // 排序
        list.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());
        return list;
    }

    /**
     * 获取看板指标
     *
     * @param corpid          公司di
     * @param chartCategoryId 分类id
     * @param nameLike        名称筛选
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-01 22:05
     * @version v1.0
     * @since v1.0
     */
    private List<ChartEntity> getChartListByCategoryId(String corpid, Long chartCategoryId, String nameLike) throws XbbException {
        Map<String, Object> param = new HashMap<>(16);
        param.put("corpid", corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("categoryId", chartCategoryId);
        param.put("nameLike", nameLike);
        param.put("enable", BasicConstant.IS_USE);
        param.put("orderByStr", "update_time desc");
        param.put(StringConstant.COLUMNS, "id,corpid,category,statistics_type,system_code,enable,chart_type,show_types,publish,name,old_name,name_en,icon,color,permissions,driver_sources,ref_types,unit,sort,explains,join_rule,remove_rule,scope_rule,power_type,item_style_option,chart_classify");
        List<ChartEntity> result = new ArrayList<>(chartModel.findEntitys(param));
        result.addAll(chartCustomModel.findEntitys(param));


        boolean standardWithFeeType = marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(corpid);
        // 判断是否是旗舰版
        Boolean ultimateWithFeeType = packageHelp.isUltimateWithFeeType(corpid);
        List<String> systemcode = Arrays.asList(SystemCodeEnum.CLUE_TOTAL_BOARD.getSystemCode(), SystemCodeEnum.CLUE_ADD_BOARD.getSystemCode(), SystemCodeEnum.CLUE_FOLLOW_BOARD.getSystemCode());
        List<ChartEntity> chartList2 = new ArrayList<>();
        for (ChartEntity chartEntity : result) {
            if (standardWithFeeType && systemcode.contains(chartEntity.getSystemCode())){
                continue;
            }
            // 只有旗舰版，首页业绩目标设置才有自定义目标
            boolean isNotUltimateAndCustom = (!ultimateWithFeeType) && Objects.equals(chartEntity.getChartType(), ChartTypeEnum.CUSTOMER_PERFORMANCE.getCode());
            if (isNotUltimateAndCustom){
                continue;
            }
            chartList2.add(chartEntity);
        }
        return chartList2;
    }

    /**
     * 获取看板下已启用指标
     *
     * @param enableList 已启用的指标id列表
     * @param chartList  指标列表，已启用指标从此列表移除
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-29 15:03
     * @version v1.0
     * @since v1.0
     */
    private List<IndexBoardChartPojo> getEnableChartList(List<IndexBoardChartSavePojo> enableList, List<ChartEntity> chartList) {
        if (enableList == null || enableList.size() == 0 || chartList == null) {
            return new ArrayList<>();
        }

        List<IndexBoardChartPojo> resultList = new ArrayList<>();
        // 已启用
        Iterator<ChartEntity> it = chartList.iterator();
        Integer statisticsType;
        while (it.hasNext()) {
            ChartEntity chartEntity = it.next();
            boolean showChart = hasShowTypes(chartEntity.getShowTypes());
            for (IndexBoardChartSavePojo savePojo : enableList) {
                Long id = savePojo.getId();
                if (id.equals(chartEntity.getId())) {
                    // 没设置过使用图表指标类型
                    statisticsType = Objects.isNull(savePojo.getStatisticsType()) ? chartEntity.getStatisticsType() : savePojo.getStatisticsType();
                    if (Objects.isNull(savePojo.getStatisticsType()) ||
                            (Objects.nonNull(savePojo.getStatisticsType()) && savePojo.getStatisticsType().equals(chartEntity.getStatisticsType()))) {
                        String unit = setUnit(chartEntity);
                        IndexBoardChartPojo chartPojo = new IndexBoardChartPojo(id, savePojo.getSort(), chartEntity.getName(), showChart, statisticsType,chartEntity.getIcon(),unit,chartEntity.getColor());
                        resultList.add(chartPojo);
                        it.remove();
                        break;
                    }
                }
            }
        }

        resultList.sort((pojo1, pojo2) -> pojo2.getSort() - pojo1.getSort());

        return resultList;
    }

    /**
     * 设置自定义指标的单位
     * @param chartEntity  图表实体
     * @return 返回单位
     */
    public String setUnit(ChartEntity chartEntity) {
        String unit = chartEntity.getUnit();
        if(Objects.equals(UnitEnum.CUSTOM.getAlias(),unit)){
            JSONObject explainJson = chartEntity.getExplains();
            if(explainJson != null && !explainJson.isEmpty()){
                unit = explainJson.get("unitValue").toString();
            }
        }else {
            UnitEnum unitEnum = UnitEnum.getByAlias(unit);
            if(unitEnum != null){
                unit = unitEnum.getName();
            }
        }
        return unit;
    }
    /**
     * 获取看板下未启用指标
     *
     * @param chartList 指标列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-29 15:05
     * @version v1.0
     * @since v1.0
     */
    private List<IndexBoardChartPojo> getDisableChartList(List<ChartEntity> chartList) throws XbbException {
        if (chartList == null || chartList.size() == 0) {
            return new ArrayList<>();
        }
        boolean standardWithFeeType = marketManagementBusinessHelp.isStandardWithFeeType(chartList.get(0).getCorpid());
        List<String> systemcode = Arrays.asList(SystemCodeEnum.CLUE_TOTAL_BOARD.getSystemCode(), SystemCodeEnum.CLUE_ADD_BOARD.getSystemCode(), SystemCodeEnum.CLUE_FOLLOW_BOARD.getSystemCode());

        List<IndexBoardChartPojo> resultList = new ArrayList<>();
        for (ChartEntity entity : chartList) {
            if (standardWithFeeType && systemcode.contains(entity.getSystemCode())){
                continue;
            }
            Long id = entity.getId();
            String name = entity.getName();
            boolean showChart = hasShowTypes(entity.getShowTypes());
            String unit = setUnit(entity);
            IndexBoardChartPojo chartPojo = new IndexBoardChartPojo(id, 0, name, showChart, entity.getStatisticsType(),entity.getIcon(),unit,entity.getColor());
            resultList.add(chartPojo);
        }
        return resultList;
    }

    /**
     * 获取首页看板ids
     *
     * @param systemIds 返回（系统看板）
     * @param customIds 返回（自定义看板）
     * @param list      数据列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-02 14:21
     * @version v1.0
     * @since v1.0
     */
    private void getConfigSaveIds(List<Long> systemIds, List<Long> customIds, List<IndexBoardSaveItemPojo> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        for (IndexBoardSaveItemPojo itemPojo : list) {
            Integer chartCategoryType = itemPojo.getChartCategoryType();
            if (chartCategoryType == ChartConstant.CHART_CATEGORY_TYPE_CATEGORY) {
                systemIds.add(itemPojo.getChartCategoryId());
            } else if (chartCategoryType == ChartConstant.CHART_CATEGORY_TYPE_CHART) {
                customIds.add(itemPojo.getChartCategoryId());
            }
        }
    }

    /**
     * 获取未启用的看板
     *
     * @param setList    看板列表
     * @param enableList 已启用看板列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-30 15:02
     * @version v1.0
     * @since v1.0
     */
    private List<IndexSetDataPojo> getDisableBoardList(List<IndexSetDataPojo> setList, List<IndexBoardSaveItemPojo> enableList) {
        List<IndexSetDataPojo> list = new ArrayList<>();
        for (IndexSetDataPojo pojo : setList) {
            long id = pojo.getChartCategoryId();
            int type = pojo.getChartCategoryType();
            boolean isDisable = false;
            for (IndexBoardSaveItemPojo itemPojo : enableList) {
                long itemId = itemPojo.getChartCategoryId();
                int itemType = itemPojo.getChartCategoryType();
                if (id == itemId && type == itemType) {
                    isDisable = false;
                    break;
                }
                isDisable = true;
            }
            if (isDisable) {
                // 设置为未启用,排序设置为0
                pojo.setEnable(BasicConstant.NO_USE);
                pojo.setSort(0);
                list.add(pojo);
            }
        }

        return list;
    }

    /**
     * 获取首页看板--系统看板展示方式（客户/合同/回款/付款/采购/工单）
     *
     * @param platform 平台（app没有表格方式）
     * @param showFlag 是否展示
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-15 14:33
     * @version v1.0
     * @since v1.0
     */
    private List<KeyValuePojo> getShowTypeList(String platform, boolean showFlag) {
        List<KeyValuePojo> list = new ArrayList<>();
        if (showFlag) {
            String key1 = ChartTypeEnum.BAR_CHART.getCode() + "";
            String value1 = ChartTypeEnum.BAR_CHART.getName();
            KeyValuePojo pojo1 = new KeyValuePojo(key1, value1);
            list.add(pojo1);

            String key2 = ChartTypeEnum.LINE_CHART.getCode() + "";
            String value2 = ChartTypeEnum.LINE_CHART.getName();
            KeyValuePojo pojo2 = new KeyValuePojo(key2, value2);
            list.add(pojo2);

            if (StringConstant.PLATFORM_WEB.equals(platform)) {
                String key3 = ChartTypeEnum.TABLE.getCode() + "";
                String value3 = ChartTypeEnum.TABLE.getName();
                KeyValuePojo pojo3 = new KeyValuePojo(key3, value3);
                list.add(pojo3);
            }
        }
        return list;
    }

    /**
     * 获取筛选项数据
     *
     * @param corpid         公司id
     * @param userId         员工id
     * @param userName       员工名字
     * @param dataPermission 员工权限
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-01 10:34
     * @version v1.0
     * @since v1.0
     */
    private IndexFilterDataPojo getFilterData(String corpid, String userId, String userName, Integer dataPermission) {
        IndexFilterDataPojo dataPojo;
        IndexFilterEntity entity = indexFilterModel.getByCorpidAndUserId(corpid, userId);
        if (entity == null) {
            dataPojo = indexHelp.getDefaultFilter(userId, userName, dataPermission);
        } else {
            JSONObject dataObject = entity.getContentData();
            try {
                dataPojo = dataObject.toJavaObject(IndexFilterDataPojo.class);
            } catch (JSONException e) {
                dataPojo = indexHelp.getDefaultFilter(userId, userName, dataPermission);
            }
        }

        return dataPojo;
    }


    /**
     * 获取x轴时间数据
     *
     * @param dataPojo   筛选pojo
     * @param timeType   时间类型
     * @param startMonth 财年开始月份
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-15 10:21
     * @version v1.0
     * @since v1.0
     */
    private List<String> getDateTitleLis(IndexFilterDataPojo dataPojo, Integer timeType, int startMonth) {
        FiscalYearTimePojo fiscalYearTimePojo = new FiscalYearTimePojo();
        BeanUtil.copyProperties(dataPojo, fiscalYearTimePojo);
        //横坐标
        return FiscalYearHelp.getDateTitleList(fiscalYearTimePojo, timeType, startMonth);
    }

    /**
     * 首页公告处理
     *
     * @param rightList  右侧看板列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-01 16:22
     * @version v1.0
     * @since v1.0
     */
    private void checkAnnouncementPojo(List<IndexInitPojo> rightList, String corpid) {
        IndexInitPojo announcementPojo = indexHelp.getPojoByAlias(rightList, ChartCategoryAliasEnum.ANNOUNCEMENT.getAlias());
        if (announcementPojo != null) {
            boolean enable = false;
            ActivityEntity activity = activityService.getLastActivity(ActivityTypeEnum.VERSION_UPGRADE.getCode(), corpid);
            // 更新公告
            if (Objects.nonNull(activity)) {
                // 设置公告模块为启用
                enable = true;
                String name = activity.getTitle();
                announcementPojo.setName(name);
                JSONObject subBusinessObj = new JSONObject();
                subBusinessObj.put("id", activity.getId());
                subBusinessObj.put("coverPicture", activity.getCoverPicture());
                subBusinessObj.put("activeUrl", activity.getActiveUrl());
                announcementPojo.setSubBusiness(subBusinessObj);
                indexHelp.replacePojoByAlias(rightList, announcementPojo, ChartCategoryAliasEnum.ANNOUNCEMENT.getAlias());
            }
            if (!enable) {
                indexHelp.removePojoByAlias(rightList, ChartCategoryAliasEnum.ANNOUNCEMENT.getAlias());
            }
        }
    }

    /**
     * 首页pk榜穿透
     *
     * @param leftList  左侧看板列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-01 16:22
     * @version v1.0
     * @since v1.0
     */
    private void leftThroughPK(List<IndexInitPojo> leftList, String corpid) throws XbbException {
        List<Long> chartIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        leftList.forEach(left -> {
            if(Objects.equals(left.getAlias(), ChartCategoryAliasEnum.PK.getAlias())){
                chartIdList.addAll(left.getIdIn());
            }
        });
        if(Objects.nonNull(chartIdList) && chartIdList.size() > 0){
            //查找图表列表
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("corpid", corpid);
            map.put("del", DelEnum.NORMAL.getDel());
            map.put("idIn", chartIdList);
            //获取pk类型的图表
            map.put("chartType", ChartTypeEnum.PK.getCode());
            List<ChartEntity> list = chartModel.findEntitys(map);
            // 获取自定义pk
            map.put("chartType", ChartTypeEnum.PK_CUSTOM.getCode());
            list.addAll(chartCustomModel.findEntitys(map));
            if (list == null || list.size() == 0) {
                throw new XbbException(StatisticsServicesErrorCodeEnum.API_ERROR_224022, StatisticsServicesErrorCodeEnum.API_ERROR_224022.getMsg(), I18nMessageUtil.getMessage(I18nStringConstant.REQUEST_PK_LIST_NOT_EXIST));
            }
            List<Long> catIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (ChartEntity chartEntity : list) {
                JSONArray category = chartEntity.getCategory();
                if(category != null){
                    List<Long> categoryIdList = JSONObject.parseArray(category.toJSONString(), Long.class);
                    // 并集
                    catIdList.addAll(categoryIdList);
                }
            }
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid", corpid);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put("negParentId", DelEnum.NORMAL.getDel());
            params.put("idIn", catIdList);
            List<ChartCategoryEntity> getChartCategoryList = chartCategoryModel.findEntitys(params);

            Map<Long, Long> chartAndCategoryIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, String> chartAndSystemCodeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> chartCategoryIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if(!getChartCategoryList.isEmpty()){

                getChartCategoryList.forEach(chartCategoryEntity -> chartCategoryIdList.add(chartCategoryEntity.getId()));

                list.forEach(chartEntity -> {
                    JSONArray category = chartEntity.getCategory();
                    if(category != null){
                        List<Long> categoryIdList = JSONObject.parseArray(category.toJSONString(), Long.class);
                        categoryIdList.retainAll(chartCategoryIdList);
                        if(Objects.equals(categoryIdList.size(), BasicConstant.ONE)){
                            chartAndCategoryIdMap.put(chartEntity.getId(), categoryIdList.get(BasicConstant.ZERO));
                            chartAndSystemCodeMap.put(chartEntity.getId(), chartEntity.getSystemCode());
                        }
                    }
                });

                leftList.forEach(left -> {
                    JSONArray childList = left.getChildList();
                    if(Objects.equals(left.getAlias(), ChartCategoryAliasEnum.PK.getAlias()) && Objects.nonNull(childList)){
                        List<ChartResultPkDetailVO> categoryIdList = JSONObject.parseArray(childList.toJSONString(), ChartResultPkDetailVO.class);
                        for(ChartResultPkDetailVO pkDetailVO : categoryIdList){
                            Long id = pkDetailVO.getId();
                            pkDetailVO.setChooseTemp(BasicConstant.ZERO);
                            if(Objects.nonNull(id)){
                                if(chartAndCategoryIdMap.containsKey(id)){
                                    Long categoryId = chartAndCategoryIdMap.get(id);
                                    pkDetailVO.setCategoryId(categoryId);
                                }
                                if(chartAndSystemCodeMap.containsKey(id)){
                                    String systemCode = chartAndSystemCodeMap.get(id);
                                    if(Objects.equals(systemCode, SystemCodeEnum.PK_CONTRACT_AMOUNT.getSystemCode()) || Objects.equals(systemCode, SystemCodeEnum.PK_CONTRACT_COUNT.getSystemCode()) ||
                                            Objects.equals(systemCode, SystemCodeEnum.PK_CUSTOMER_ADD.getSystemCode()) || Objects.equals(systemCode, SystemCodeEnum.PK_OPPORTUNITY_ADD_COUNT.getSystemCode()) ||
                                            Objects.equals(systemCode, SystemCodeEnum.PK_OPPORTUNITY_ADD_AMOUNT.getSystemCode()) || Objects.equals(systemCode, SystemCodeEnum.PK_CONTRACT_PROFIT.getSystemCode())){
                                        pkDetailVO.setChooseTemp(BasicConstant.ONE);
                                    }
                                }
                            }
                        }
                        JSONArray array= JSONArray.parseArray(JSON.toJSONString(categoryIdList));
                        left.setChildList(array);
                    }
                });
            }
        }
    }

    /**
     * 判断首页右侧看板，攻略卡片是否开启
     *
     * @param rightList 首页右侧
     * @param corpid 公司id
     * @author 徐俊杰
     * @date 2019/10/24 15:09
     * @since v1.0
     */
    private void checkRaiders(List<IndexInitPojo> rightList, String corpid) {
        Iterator<IndexInitPojo> rightIterator = rightList.iterator();
        while (rightIterator.hasNext()) {
            IndexInitPojo indexInitPojo = rightIterator.next();
            String alias = indexInitPojo.getAlias();
            if (Objects.equals(alias, ChartCategoryAliasEnum.RAIDERS.getAlias())) {
                String raidersAlias = CompanyConfigEnum.RAIDERS.getAlias();
                //获取攻略的company-config
                CompanyConfigEntity raidersConfig = companyConfigModel.getByConfigAlias(raidersAlias, corpid);
                //查不到则移除
                if (raidersConfig == null) {
                    rightIterator.remove();
                } else {
                    String configValue = raidersConfig.getConfigValue();
                    //查到如果是不开启则移除
                    if (Objects.equals(Integer.valueOf(configValue), RaidersConstant.NOT_ENABLE)) {
                        rightIterator.remove();
                    }
                }
            }
        }
    }

    /**
     * 判断首页右侧看板，攻略卡片是否开启
     *
     * @param chartCategoryEntity 图表分类实体
     * @param corpid 公司id
     * @return boolean
     * @author 徐俊杰
     * @date 2019/10/30 9:41
     * @since v1.0
     */
    private boolean checkRaiders(ChartCategoryEntity chartCategoryEntity, String corpid) {
        String alias = chartCategoryEntity.getAlias();
        if (Objects.equals(alias, ChartCategoryAliasEnum.RAIDERS.getAlias())) {
            String raidersAlias = CompanyConfigEnum.RAIDERS.getAlias();
            //获取攻略的company-config
            CompanyConfigEntity raidersConfig = companyConfigModel.getByConfigAlias(raidersAlias, corpid);
            //查不到则返回false
            if (raidersConfig == null) {
                return false;
            } else {
                // 价值攻略始终展示
                /*String configValue = raidersConfig.getConfigValue();
                //查到如果是开启则返回true
                return Objects.equals(Integer.valueOf(configValue), RaidersConstant.ENABLE);*/
                return true;
            }
        } else {
            //不是价值攻略则返回true
            return false;
        }
    }

    /**
     * 获取销售简报
     *
     * @param corpid 公司id
     * @param userId 用户id
     * @param list   展示列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-26 15:44
     * @version v1.0
     * @since v1.0
     */
    private JSONObject getSalesReport(String corpid, String userId, List<IndexInitPojo> list) {
        IndexInitPojo salesReportPojo = indexHelp.getPojoByAlias(list, ChartCategoryAliasEnum.SALES_REPORT.getAlias());
        if (salesReportPojo != null) {
            PushEntity pushEntity = messageListService.indexSalesReport(corpid, userId);
            if (pushEntity != null) {
                // 18837 App首页小数简报缺少title信息。
                // 标题、开始时间，结束时间
                OAMessage.Body body;
                PushRefTypePojo.SalesReportOptions salesReportOptions;
                try {
                    OAMessage msgOjbect = JSONObject.parseObject(pushEntity.getMsg(), OAMessage.class);
                    body = msgOjbect.body;
                    String pushEntityRefType = pushEntity.getRefType();
                    JSONObject pushEntityRefTypeObj = JSONObject.parseObject(pushEntityRefType);
                    salesReportOptions = JSONObject.parseObject(pushEntityRefTypeObj.getString("options"), PushRefTypePojo.SalesReportOptions.class);
                } catch (JSONException e) {
                    body = null;
                    salesReportOptions = null;
                }
                if (Objects.isNull(body) || Objects.isNull(salesReportOptions)) {
                    return null;
                }

                JSONObject salesObject = new JSONObject();
                salesObject.put("title", body.title);
                salesObject.put("start", salesReportOptions.getStart());
                salesObject.put("end", salesReportOptions.getEnd());

                return salesObject;
            }
            indexHelp.removePojoByAlias(list, ChartCategoryAliasEnum.SALES_REPORT.getAlias());
        }
        return null;
    }

    /**
     * 看板下指标保存参数验证
     *
     * @param configDTO 入参
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-29 16:21
     * @version v1.0
     * @since v1.0
     */
    private void checkChartSave(IndexBoardChartSaveConfigDTO configDTO) throws XbbException {
        String corpid = configDTO.getCorpid();
        Long chartCategoryId = configDTO.getChartCategoryId();
        List<IndexBoardChartSavePojo> enableList = configDTO.getEnableList();
        // 指标最大数量:12个
        if (enableList.size() > CHART_MAX_COUNT) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.BOARD_POSITION_FULL);
        }
        // 分类是否存在
        ChartCategoryEntity categoryEntity = chartCategoryModel.getByKey(chartCategoryId, corpid);
        if (categoryEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.BOARD_NOT_EXIST_OR_DELETED);
        }

        List<Long> enableIds = new ArrayList<>();
        for (IndexBoardChartSavePojo savePojo : enableList) {
            enableIds.add(savePojo.getId());
        }

        // 图表指标ids
        List<Long> showChartIds = new ArrayList<>();

        // 验证指标
        List<ChartEntity> chartList = getChartListByCategoryId(corpid, chartCategoryId, null);
        for (ChartEntity entity : chartList) {
            // 图表指标
            boolean showChart = hasShowTypes(entity.getShowTypes());
            if (showChart) {
                showChartIds.add(entity.getId());
            }
        }
        // 图表上的指标不能为空
        if (showChartIds.size() > 0) {
            showChartIds.retainAll(enableIds);
            if (showChartIds.size() == 0) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.CHART_INDICATOR_NEED_ENABLE);
            }
        }
    }

    /**
     * 看板筛选项时间参数验证
     *
     * @param saveFilterDTO 参数
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-02-27 15:18
     * @version v1.0
     * @since v1.0
     */
    private void checkTime(IndexSaveFilterDTO saveFilterDTO) throws XbbException {
        Integer timeType = saveFilterDTO.getTimeType();
        TimeTypeEnum timeTypeEnum = TimeTypeEnum.getByCode(timeType);
        if (timeTypeEnum == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.INCORRECT_TIME_TYPE_SELECTED);
        }

        Integer year = saveFilterDTO.getYear();
        Integer month = saveFilterDTO.getMonth();
        Integer season = saveFilterDTO.getSeason();
        String startTimeStr = saveFilterDTO.getStartTime();
        String endTimeStr = saveFilterDTO.getEndTime();
        long startTime = DateUtil.getInt(startTimeStr, DateUtil.SDFDate);
        long endTime = DateUtil.getInt(endTimeStr, DateUtil.SDFDate);
        switch (timeTypeEnum) {
            // 月
            case MONTH:
                if (year != null) {
                    if (month < BasicConstant.MIN_MONTH || month > BasicConstant.MAX_MONTH) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.INCORRECT_MONTH);
                    }
                }
                break;
            // 季度
            case SEASON:
                if (year != null) {
                    if (season < BasicConstant.MIN_SEASON || season > BasicConstant.MAX_SEASON) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.INCORRECT_QUARTER);
                    }
                }
                break;
            // 年、半年
            case YEAR:
            case YEAR_HALF_UP:
            case YEAR_HALF_DOWN:
                if (year == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.YEAR_CANNOT_EMPTY);
                }
                break;
            // 自定义时间
            case CUSTOM:
            case UP_TO_NOW:
            case DYNAMIC:
                if (startTime > endTime) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, I18nStringConstant.END_TIME_REGULATIONS);
                }
                break;
            default:
                break;
        }
    }
    /**
     * 处理首页配置的内层chart
     * @param initDTO
     * @param list 启用、不启用的内层chart
     * @return void
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void packageChart(ChartCategoryInitDTO initDTO, List<IndexBoardChartSavePojo> list){
        for (IndexBoardChartSavePojo indexBoardChartSavePojo : list) {
            if (Objects.equals(indexBoardChartSavePojo.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                initDTO.getCustomChartIdSet().add(indexBoardChartSavePojo.getId());
            } else {
                initDTO.getSystemChartIdSet().add(indexBoardChartSavePojo.getId());
            }
        }
    }
    /**
     * 把获取到的分类、图表封装为map
     * @param companyData  分类、图表信息
     * @return void
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void formatCompanyData(UserVO loginUser, ChartCategoryInitVO companyData){
        List<ChartCategoryEntity> categoryList = companyData.getCategoryList();
        List<ChartEntity> chartList = companyData.getChartList();
        Map<Long, ChartCategoryEntity> categoryMap = companyData.getCategoryMap();
        Map<Long, ChartEntity> systemChartMap = companyData.getSystemChartMap();
        Map<Long, ChartEntity> customChartMap = companyData.getCustomChartMap();
        for (ChartCategoryEntity entity : categoryList) {
            if (Objects.equals(LocaleContextHolder.getLocale().getLanguage(), I18nStringConstant.ENGLISH_LANGUAGE)) {
                String name = entity.getName();
                String nameEn = entity.getNameEn();
                entity.setName(name);
                entity.setNameEn(nameEn);
            }
            categoryMap.put(entity.getId(), entity);
        }
        for (ChartEntity entity : chartList) {
            if (Objects.equals(LocaleContextHolder.getLocale().getLanguage(), I18nStringConstant.ENGLISH_LANGUAGE)) {
                String name = entity.getName();
                String nameEn = entity.getNameEn();
                entity.setName(name);
                entity.setNameEn(nameEn);
            }
            if (Objects.equals(entity.getStatisticsType(), StatisticsTypeEnum.CUSTOM_STATISTIC.getCode())) {
                customChartMap.put(entity.getId(), entity);
            } else {
                systemChartMap.put(entity.getId(), entity);
            }
        }
        companyData.setCategoryMap(categoryMap);
        companyData.setSystemChartMap(systemChartMap);
        companyData.setCustomChartMap(customChartMap);
    }

    private JSONObject getCustomIndexSet(Long homePageId,String corpid) throws XbbException {
        // 管理员自定义首页分配
        HomePageManageEntity homePageManageEntity = null;
        if ( null != homePageId){
            homePageManageEntity = homePageManageModel.getByKey(homePageId,corpid);
            if (null == homePageManageEntity){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018,  SystemErrorCodeEnum.API_ERROR_100018.getMsg());
            }
        }
        if (null != homePageManageEntity){
            JSONObject refIds = homePageManageEntity.getRefIds();
            if (null != refIds){
                JSONObject resultObject = new JSONObject();
                for (BoardTypeEnum boardEnum : BoardTypeEnum.values()) {
                    Long refId = refIds.getLong(boardEnum.getAlias());
                    if (null != refId) {
                        IndexSetEntity indexSetEntity = indexSetModel.getByKey(refId, corpid);
                        List<IndexSetDataPojo> list = null;
                        try {
                            if (null != indexSetEntity){
                                list = indexSetEntity.getContentData().toJavaList(IndexSetDataPojo.class);
                            }
                        } catch (JSONException e) {
                            list = null;
                        }
                        if (null != list){
                            resultObject.put(boardEnum.getAlias(),list);
                        }
                    }
                }
                return resultObject;
            }
        }
        return null;
    }

    private IndexSetEntity getSetEntity(Long homePageId,String corpid,Integer boardType) throws XbbException {
        // 管理员自定义首页分配
        HomePageManageEntity homePageManageEntity = null;
        if ( null != homePageId){
            homePageManageEntity = homePageManageModel.getByKey(homePageId,corpid);
            if (null == homePageManageEntity){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018,  SystemErrorCodeEnum.API_ERROR_100018.getMsg());
            }
        }
        JSONObject refIds = homePageManageEntity.getRefIds();
        BoardTypeEnum boardTypeEnum = BoardTypeEnum.getByCode(boardType);
        Long refId = refIds.getLong(boardTypeEnum.getAlias());
        if (null != refId) {
            IndexSetEntity indexSetEntity = indexSetModel.getByKey(refId, corpid);
            return indexSetEntity;
        }
        return null;
    }

    /**
     * 保存单个app看板
     * @param saveSingleConfigAppDTO
     * @return
     * @throws XbbException
     */
    public IndexBoardSaveSingleConfigVO saveSingleConfigApp(IndexBoardSaveSingleConfigAppDTO saveSingleConfigAppDTO) throws XbbException {
        IndexBoardSaveSingleConfigVO saveSingleConfigVO = new IndexBoardSaveSingleConfigVO();

        String corpid = saveSingleConfigAppDTO.getCorpid();
        String userId = saveSingleConfigAppDTO.getUserId();
        String platform = saveSingleConfigAppDTO.getPlatform();
        Integer customPageFlag = saveSingleConfigAppDTO.getCustomPageFlag();
        List<IndexBoardSaveItemPojo> enableList = saveSingleConfigAppDTO.getEnableList();
        BoardTypeEnum boardTypeEnum = BoardTypeEnum.getByAlias(saveSingleConfigAppDTO.getBoardAlias());
        if (null == boardTypeEnum){
            // 抛出异常未知看板
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028);
        }

        if (enableList.size() > DINGTALK_BOARD_COUNT) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.ENABLED__BOARDS_CANNOT_EXCEED, DINGTALK_BOARD_COUNT);
        }

        // TODO 获取当前数据(角色修改后期考虑)
        ChartCategoryInitVO companyData = saveSingleConfigAppDTO.getCompanyData();
        List<ChartCategoryEntity> categoryList = companyData.getCategoryList();
        List<ChartEntity> chartList = companyData.getChartList();

        // todo 日志map优化
        HashMap<Long, String> categoryListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        HashMap<String, String> chartListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        categoryList.forEach(category -> categoryListMap.put(category.getId(), category.getName()));
        chartList.forEach(chart -> chartListMap.put(String.format(SymbolConstant.UNDERLINE, chart.getStatisticsType(),chart.getId()), chart.getName()));

        List<Long> systemIds = new ArrayList<>();
        List<Long> customIds = new ArrayList<>();
        getConfigSaveIds(systemIds, customIds, enableList);
        List<Long> categoryIds = new ArrayList<>();
        List<Long> chartIds = new ArrayList<>();
        for (ChartCategoryEntity categoryEntity : categoryList) {
            categoryIds.add(categoryEntity.getId());
        }
        for (ChartEntity chartEntity : chartList) {
            chartIds.add(chartEntity.getId());
        }

        for (Long id : systemIds) {
            if (!categoryIds.contains(id)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.BOARD_NOT_EXIST);
            }
        }
        for (Long id : customIds) {
            if (!chartIds.contains(id)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.BOARD_NOT_EXIST);
            }
        }
        // 获取个人配置
        IndexSetEntity setEntity;
        if (Objects.equals(customPageFlag,HomePageCustomTypeEnum.IS_CUSTOM.getCode())){
            Long refId = saveSingleConfigAppDTO.getRefId();
            if (null == refId){
                setEntity = getSetEntity(corpid, "0", StringConstant.PLATFORM_DINGTALK, boardTypeEnum.getCode());
                setEntity.setCustomPageFlag(1);
                setEntity.setId(null);
                setEntity.setUserId(userId);
            }else {
                setEntity = indexSetModel.getByKey(refId,corpid);
            }
        }else {
            setEntity = getSetEntity(corpid, userId, StringConstant.PLATFORM_DINGTALK, boardTypeEnum.getCode());
        }
        // 获取个人配置
        List<IndexSetDataPojo> setDBList = setEntity.getContentData().toJavaList(IndexSetDataPojo.class);

        // 获取公司配置
        List<IndexSetDataPojo> companyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, boardTypeEnum.getCode());
        // 过虑配置
        Boolean isCustom = Objects.equals(saveSingleConfigAppDTO.getCustomPageFlag(),1);
        List<IndexSetDataPojo> setDataList = checkConfig4Save(companyList, setDBList,isCustom);

        // 原先看板ID todo id会相同
        List<Long> oldEnableDataId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        setDataList.forEach(item -> {
            if(Objects.equals(item.getEnable(), 1)){
                oldEnableDataId.add(item.getChartCategoryId());
            }
        });

        // 未启用看板后端处理
        List<IndexSetDataPojo> disableList = getDisableBoardList(setDataList, enableList);

        // 数据
        List<IndexSetDataPojo> setData = getEnableConfig(setDataList, enableList, companyData);
        setData.addAll(disableList);

        // 保存配置
        JSONArray saveData = new JSONArray();
        saveData.addAll(setData);
        setEntity.setContentData(saveData);
        try {
            indexSetModel.save(setEntity);
        } catch (Exception e) {
            LOG.error("保存首页看板公司配置失败",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        // 管理员分配自定义自定义首页不用日志
        if (Objects.equals(customPageFlag,HomePageCustomTypeEnum.IS_CUSTOM.getCode())){
            saveSingleConfigVO.setId(setEntity.getId());
            return saveSingleConfigVO;
        }

        // todo 日志部分也要根据statistics做区分
        List<Long> newSystemIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        enableList.forEach(item -> newSystemIds.add(item.getChartCategoryId()));
        List<Long> newOldLeftEnableDataId = new ArrayList<>(oldEnableDataId);
        // 利用差集，配置内容比较：A:1,2,3,4  B1:1,2,3,4,5  B2:1,3,4  B3:1,2,5
        oldEnableDataId.removeAll(newSystemIds);
        newSystemIds.removeAll(newOldLeftEnableDataId);

        String loginUserName = saveSingleConfigAppDTO.getLoginUserName();
        String memo;
        List<String> updateNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        oldEnableDataId.forEach(dataId -> updateNameList.add(categoryListMap.get(dataId)));
        String updateItem = StringUtils.join(updateNameList, "，");

        List<String> leftNameList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        newSystemIds.forEach(leftId -> leftNameList.add(categoryListMap.get(leftId)));
        String enableItem = StringUtils.join(leftNameList, "，");

        // 例：A:1,2,3,4  B1:1,2,3,4,5 说明没有关闭任何看板
        if(Objects.equals(oldEnableDataId.size(), 0)){
            if(newSystemIds.size() > 1){
                // 例：B1:1,2,3,4,5  A:1,2,3,4 说明只是开启了看板
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_HOME_BOARD), loginUserName, newSystemIds.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(OperateTypeEnum.ENABLE.getName());
                infoArrPojo.setContent(enableItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                        "", "", memo, saveSingleConfigAppDTO.getHttpHeader());
            } else if(Objects.equals(newSystemIds.size(), 1)){
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_HOME_BOARD), loginUserName, OperateTypeEnum.ENABLE.getName(), enableItem);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                        newSystemIds.get(0).toString(), enableItem, memo, saveSingleConfigAppDTO.getHttpHeader());
            }
        } else {
            // 例：A:1,2,3,4  (B2:1,3,4 或 B3:1,2,5) 说明关闭或并开启任何看板
            if(newSystemIds.size() > 0){
                // 例：A:1,2,3,4  B3:1,2,5  开启5，关闭3,4
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_HOME_BOARD), loginUserName, newSystemIds.size() + oldEnableDataId.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTab(OperateTypeEnum.ENABLE.getName());
                infoArrPojo.setTitle(OperateTypeEnum.ENABLE.getName());
                infoArrPojo.setContent(enableItem);
                infoArrPojoList.add(infoArrPojo);

                InfoArrPojo arrPojo = new InfoArrPojo();
                arrPojo.setTab(OperateTypeEnum.CLOSE.getName());
                arrPojo.setTitle(OperateTypeEnum.CLOSE.getName());
                arrPojo.setContent(updateItem);
                infoArrPojoList.add(arrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                        "", "", memo, saveSingleConfigAppDTO.getHttpHeader());
            } else {
                // 例：A:1,2,3,4  B2:1,3,4 说明只是关闭了看板
                if(oldEnableDataId.size() > 1){
                    // 例：B1:1,2,3,4,5  A:1,2,3,4 说明只是开启了看板
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_UPDATE_HOME_BOARD), loginUserName, oldEnableDataId.size());
                    List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    InfoArrPojo infoArrPojo = new InfoArrPojo();
                    infoArrPojo.setTitle(OperateTypeEnum.CLOSE.getName());
                    infoArrPojo.setContent(updateItem);
                    infoArrPojoList.add(infoArrPojo);
                    mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                            "", "", memo, saveSingleConfigAppDTO.getHttpHeader());
                } else if(Objects.equals(oldEnableDataId.size(), 1)){
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_HOME_BOARD), loginUserName, OperateTypeEnum.CLOSE.getName(), updateItem);
                    mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.HOME_BOARD_SET, OperateTypeEnum.EDIT,
                            oldEnableDataId.get(0).toString(), updateItem, memo, saveSingleConfigAppDTO.getHttpHeader());
                }
            }
        }

        return saveSingleConfigVO;
    }

    /**
     * 封装单个保存app-看板的dto
     * @param saveSingleConfigAppDTO
     * @param saveConfigAppDTO
     * @param boardAlias
     * @param companyData
     * @param refId
     * @param enableList
     */
    public void packageSaveConfigAppDto(IndexBoardSaveSingleConfigAppDTO saveSingleConfigAppDTO,IndexBoardSaveConfigAppDTO saveConfigAppDTO,String boardAlias,ChartCategoryInitVO companyData,Long refId,List<IndexBoardSaveItemPojo> enableList){
        saveSingleConfigAppDTO.setEnableList(enableList);
        saveSingleConfigAppDTO.setCustomPageFlag(saveConfigAppDTO.getCustomPageFlag());
        saveSingleConfigAppDTO.setCorpid(saveConfigAppDTO.getCorpid());
        saveSingleConfigAppDTO.setPlatform(saveConfigAppDTO.getPlatform());
        saveSingleConfigAppDTO.setUserId(saveConfigAppDTO.getUserId());
        saveSingleConfigAppDTO.setBoardAlias(boardAlias);
        saveSingleConfigAppDTO.setCompanyData(companyData);
        saveSingleConfigAppDTO.setRefId(refId);
    }

    /**
     * 更新经典模式下的app看板
     * @param saveConfigAppDTO
     * @param companyData
     * @param enableList
     * @param refIds
     * @return
     * @throws XbbException
     */
    public JSONObject saveClassicConfigApp(IndexBoardSaveConfigAppDTO saveConfigAppDTO,ChartCategoryInitVO companyData,List<IndexBoardSaveItemPojo> enableList,JSONObject refIds) throws XbbException {
        // 更新经典看板
        IndexBoardSaveSingleConfigAppDTO saveSingleConfigAppDTO = new IndexBoardSaveSingleConfigAppDTO();
        Long dingTalkRefId = null;
        if (null != refIds){
            // 不为null则编辑
            dingTalkRefId = refIds.getLong(BoardTypeEnum.DINGTALK.getAlias());
        }
        // 封装dto
        packageSaveConfigAppDto(saveSingleConfigAppDTO,saveConfigAppDTO,BoardTypeEnum.DINGTALK.getAlias(),companyData,dingTalkRefId,enableList);
        IndexBoardSaveSingleConfigVO saveSingleConfigVO = saveSingleConfigApp(saveSingleConfigAppDTO);
        JSONObject result = new JSONObject();
        Long id = saveSingleConfigVO.getId();
        if (null != id){
            result.put(BoardTypeEnum.DINGTALK.getAlias(),id);
        }
        return result;
    }

    /**
     * 更新专注模式下的看板
     * @param saveConfigAppDTO
     * @param companyData
     * @param focusCategoryEnableList
     * @param focusWorkEnableList
     * @param refIds
     * @return
     * @throws XbbException
     */
    public JSONObject saveFocusConfigApp(IndexBoardSaveConfigAppDTO saveConfigAppDTO,ChartCategoryInitVO companyData,List<IndexBoardSaveItemPojo> focusCategoryEnableList,List<IndexBoardSaveItemPojo> focusWorkEnableList,JSONObject refIds) throws XbbException {
        // 更新专注模式下的两种app看板
        IndexBoardSaveSingleConfigAppDTO focusCategorySaveSingleConfigAppDTO = new IndexBoardSaveSingleConfigAppDTO();
        IndexBoardSaveSingleConfigAppDTO focusWorkSaveSingleConfigAppDTO = new IndexBoardSaveSingleConfigAppDTO();
        Long focusDingTalkCategoryRefId = null;
        Long focusDingTalkWorkRefId = null;
        if (null != refIds){
            // 编辑
            focusDingTalkCategoryRefId = refIds.getLong(BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getAlias());
            focusDingTalkWorkRefId = refIds.getLong(BoardTypeEnum.FOCUS_DINGTALK_WORK.getAlias());
        }
        // 封装dto
        packageSaveConfigAppDto(focusCategorySaveSingleConfigAppDTO,saveConfigAppDTO,BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getAlias(),companyData,focusDingTalkCategoryRefId,focusCategoryEnableList);
        packageSaveConfigAppDto(focusWorkSaveSingleConfigAppDTO,saveConfigAppDTO,BoardTypeEnum.FOCUS_DINGTALK_WORK.getAlias(),companyData,focusDingTalkWorkRefId,focusWorkEnableList);
        IndexBoardSaveSingleConfigVO categorySaveSingleConfigVO = saveSingleConfigApp(focusCategorySaveSingleConfigAppDTO);
        IndexBoardSaveSingleConfigVO workSaveSingleConfigVO = saveSingleConfigApp(focusWorkSaveSingleConfigAppDTO);
        JSONObject result =  new JSONObject();
        Long leftId = categorySaveSingleConfigVO.getId();
        Long rightId = workSaveSingleConfigVO.getId();
        if (null != leftId && null != rightId){
            result.put(BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getAlias(),leftId);
            result.put(BoardTypeEnum.FOCUS_DINGTALK_WORK.getAlias(),rightId);
        }
        return result;
    }
    /**
     * 获取setEntity
     * @param customPageFlag
     * @param refIds
     * @param corpid
     * @param userId
     * @throws XbbException
     */
    private Map<String,IndexSetEntity> packageSetEntity(Integer customPageFlag,JSONObject refIds,String corpid,String userId) throws XbbException {
        IndexSetEntity leftSetEntity;
        IndexSetEntity rightSetEntity;
        Map<String,IndexSetEntity> indexSetEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.equals(customPageFlag,HomePageCustomTypeEnum.IS_CUSTOM.getCode())){
            Long leftId = refIds.getLong(BoardTypeEnum.WEB_LEFT.getAlias());
            Long rightId = refIds.getLong(BoardTypeEnum.WEB_RIGHT.getAlias());
            if (null == leftId || null == rightId){
                leftSetEntity = getSetEntity(corpid, "0", StringConstant.PLATFORM_DINGTALK, BoardTypeEnum.WEB_LEFT.getCode());
                rightSetEntity = getSetEntity(corpid, "0", StringConstant.PLATFORM_DINGTALK, BoardTypeEnum.WEB_RIGHT.getCode());
                leftSetEntity.setCustomPageFlag(1);
                leftSetEntity.setId(null);
                leftSetEntity.setUserId(userId);
                rightSetEntity.setCustomPageFlag(1);
                rightSetEntity.setUserId(userId);
                rightSetEntity.setId(null);
            }else {
                leftSetEntity = indexSetModel.getByKey(leftId,corpid);
                rightSetEntity = indexSetModel.getByKey(rightId,corpid);
            }
        }else {
            leftSetEntity = getSetEntity(corpid, userId, StringConstant.PLATFORM_DINGTALK, BoardTypeEnum.WEB_LEFT.getCode());
            rightSetEntity = getSetEntity(corpid, userId, StringConstant.PLATFORM_DINGTALK, BoardTypeEnum.WEB_RIGHT.getCode());
        }
        indexSetEntityMap.put(BoardTypeEnum.WEB_LEFT.getAlias(),leftSetEntity);
        indexSetEntityMap.put(BoardTypeEnum.WEB_RIGHT.getAlias(),rightSetEntity);
        return indexSetEntityMap;
    }

    /**
     * 专注模式下app首页配置获取
     * @param getConfigDTO
     * @return
     * @throws XbbException
     */
    public IndexBoardGetConfigAppVO getFocusConfigApp(IndexBoardGetConfigDTO getConfigDTO) throws XbbException {
        IndexBoardGetConfigAppVO getConfigAppVO = new IndexBoardGetConfigAppVO();

        String corpid = getConfigDTO.getCorpid();
        String userId = getConfigDTO.getUserId();
        String platform = getConfigDTO.getPlatform();
        // 获取个人配置
        List<IndexSetDataPojo> focusCategorySetDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode());
        List<IndexSetDataPojo> focusWorkSetDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.FOCUS_DINGTALK_WORK.getCode());
        // 获取公司配置
        List<IndexSetDataPojo> focusCategoryCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.FOCUS_DINGTALK_CATEGORY.getCode());
        List<IndexSetDataPojo> focusWorkCompanyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.FOCUS_DINGTALK_WORK.getCode());
        // 过虑配置
        Boolean isCustom = null != getConfigDTO.getHomePageId();
        List<IndexSetDataPojo> focusCategorySetDataList = checkConfig4Save(focusCategoryCompanyList, focusCategorySetDBList,isCustom);
        List<IndexSetDataPojo> focusWorkSetDataList = checkConfig4Save(focusWorkCompanyList, focusWorkSetDBList,isCustom);
        // 获取当前数据
        ChartCategoryInitVO companyData = getCompanyData(corpid, userId, platform, focusCategorySetDataList, focusWorkSetDataList);
        // 权限等过滤
        filter(null,null,companyData,corpid,getConfigDTO.getLoginUser(),null,null,null,focusCategorySetDataList,focusWorkSetDataList);

        // 封装展示数据
        List<IndexBoardGetConfigAppPojo> focusCategoryList = formatConfigApp(focusCategorySetDataList, companyData,true);
        List<IndexBoardGetConfigAppPojo> focusWorkList = formatConfigApp(focusWorkSetDataList, companyData,true);
        LOG.error("focusCategoryList:"+focusCategoryList);
        LOG.error("focusWorkList:"+focusWorkList);
        getConfigAppVO.setFocusDingTalkCategoryList(focusCategoryList);
        getConfigAppVO.setFocusDingTalkWorkList(focusWorkList);
        LOG.error("end configApp");
        return getConfigAppVO;
    }
    /**
     * 经典模式下app首页配置获取
     * @param getConfigDTO
     * @return
     * @throws XbbException
     */
    public IndexBoardGetConfigAppVO getClassicConfigApp(IndexBoardGetConfigDTO getConfigDTO) throws XbbException {
        IndexBoardGetConfigAppVO getConfigAppVO = new IndexBoardGetConfigAppVO();

        String corpid = getConfigDTO.getCorpid();
        String userId = getConfigDTO.getUserId();
        String platform = getConfigDTO.getPlatform();
        // 获取个人配置
        List<IndexSetDataPojo> setDBList = systemChartHelp.getUserConfig(corpid, userId, BoardTypeEnum.DINGTALK.getCode());
        // 获取公司配置
        List<IndexSetDataPojo> companyList = systemChartHelp.getCompanyConfig(corpid, userId, platform, BoardTypeEnum.DINGTALK.getCode());
        // 过虑配置
        Boolean isCustom = null != getConfigDTO.getHomePageId();
        List<IndexSetDataPojo> setDataList = checkConfig4Save(companyList, setDBList,isCustom);
        // 获取当前数据
        ChartCategoryInitVO companyData = getCompanyData(corpid, userId, platform, setDataList, null);
        // 权限等过滤
        filter(null,companyData,null,corpid,getConfigDTO.getLoginUser(),null,null,setDataList,null,null);
        // 封装展示数据
        List<IndexBoardGetConfigAppPojo> setList = formatConfigApp(setDataList, companyData,false);
        getConfigAppVO.setList(setList);
        return getConfigAppVO;
    }

    private void setCommunicatePlanPermission(List<IndexInitPojo> rightSetList,IndexBoardInitVO indexBoardInitVO){
        indexBoardInitVO.setCommunicatePlan(false);
        for (IndexInitPojo item : rightSetList) {
            if (Objects.equals(ChartCategoryAliasEnum.COMMUNICATE_PLAN.getAlias(), item.getAlias())) {
                indexBoardInitVO.setCommunicatePlan(true);
                break;
            }
        }
    }
    private void setCommunicatePlanHidden(List<IndexInitPojo> rightSetList,Integer hidden){
        for (IndexInitPojo item : rightSetList) {
            if (Objects.equals(ChartCategoryAliasEnum.COMMUNICATE_PLAN.getAlias(), item.getAlias())) {
                item.setHidden(hidden);
                break;
            }
        }
    }
}
